当我用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();
}
Run Code Online (Sandbox Code Playgroud)
为什么我得到这个错误,是什么样的区别str在课堂上test和x在main功能?
Mr.*_*C64 10
在您的类中,您必须显式指定数组大小:
class test {
...
private:
// If you really want a raw C-style char array...
char str[10] = "123456789"; // 9 digits + NUL terminator
};
Run Code Online (Sandbox Code Playgroud)
或者你可以简单地使用a std::string(我认为在C++代码中通常比使用原始C风格的字符串好得多):
#include <string>
...
class test {
...
private:
std::string str = "123456789";
};
Run Code Online (Sandbox Code Playgroud)