当我使用g ++ 4.8.2编译下面的代码时,我收到错误。
#include <iostream>
using namespace std;
class test {
public:
void print() {
cout << str << endl;
}
private:
char str[] = "123456789"; // error: initializer-string for array of chars
// is too long
};
int main() {
char x[] = "987654321";
cout << x << endl;
test temp;
temp.print();
}
为什么我会收到错误,str
课程test
和x
main
{{1}}之间有什么区别?
答案 0 :(得分:10)
在您的课程中,您必须显式指定数组大小:
class test {
...
private:
// If you really want a raw C-style char array...
char str[10] = "123456789"; // 9 digits + NUL terminator
};
或者你可以简单地使用std::string
(我认为在C ++代码中通常比使用原始C风格的字符串要好得多):
#include <string>
...
class test {
...
private:
std::string str = "123456789";
};
答案 1 :(得分:2)
您不能在结构/类中拥有未知大小的数组,您需要设置数组大小。
或者更好的是,对字符串使用std::string
。这就是它的目的。
答案 2 :(得分:1)
我意识到你在问什么并重写我的整个回复。 你不应该在班上初级化。 您只声明要使用的变量/方法。 只有在那之后,才使用你的类来创建对象。
从那时起设置对象变量的值。
例如:
class Test
{
public:
int num; //You don't intialie value here
};
int main
{
Test testObj();
testObj.num = 100;
}
但是,如果将变量设置为private,则需要在类中创建一个函数来访问类成员。例如setNum()
或者,您可以使用构造函数设置变量,并在对象创建期间将其作为参数输入插入。
class Test
{
public:
Test(int); //Constructor
private:
int num; //You don't intialie value here
};
Test::Test(int value)
{
this -> num = value;
}
int main
{
Test testObj(100); //set num to 100
}
如果您想使用班级成员函数访问它,您可以这样做,但当然您必须先在班级中定义setNum()
。
testObj.setNum(100);
我知道你在问char [],但我给你的例子是关于int的。这不是代码中的问题。无论是int还是char [],都应该避免在类中直接声明它。 看起来你的代码的主要问题不在于你是使用char []还是char *。 你不应该在班上初始化你的价值观。
答案 3 :(得分:0)
如果你真的知道你不打算修改字符串而且总是一样,那么你可以改为const char *str = "123456789";
答案 4 :(得分:0)
您需要提供char数组的大小。如果您不知道字符串的大小或其大小是动态的,则可以使用指针。如果这样做,请确保不要忘记添加空终止字符。
答案 5 :(得分:0)
区别在于
class foo {
class y; // Instance Variable
void foo(){
class x; // Method Variable
// use x and y
}
}
char*
的实例变量将起作用char* x = "foobar"
。编译器可能允许将方法变量设置为char[]
,因为范围有限。我试图查找一些文献来解释不同的治疗方法。