C++ 初始化类中的字符数组
当我用g++4.8.2编译下面的代码时,我得到一个错误C++ 初始化类中的字符数组,c++,g++,C++,G++,当我用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 char
#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();
}
#包括
使用名称空间std;
课堂测试{
公众:
作废打印(){
cout在结构/类中不能有大小未知的数组,需要设置数组大小
或者更好的是,用于字符串。这就是它的用途。如果你真的知道你不会修改字符串,而且总是一样的,你可以改为这样做。const char*str=“123456789”
我意识到你的要求并重写了我的整个回复。
您不应该在类中进行初始化。
您只声明要使用的变量/方法。
只有在这之后,才能使用类创建对象
从那时起设置对象变量的值
例如:
class Test
{
public:
int num; //You don't intialie value here
};
int main
{
Test testObj();
testObj.num = 100;
}
但是,如果将变量设置为private,则需要在类中创建一个函数来访问类成员
或者,您可以使用构造函数设置变量,并在对象创建期间将其作为参数输入插入
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*。
您不应该在类中初始化值。您需要提供字符数组的大小。如果您不知道字符串的大小或其大小是动态的,则可以使用指针。如果这样做,请确保不要忘记添加空终止字符。在类中,您必须显式指定数组的大小尺寸:
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样式字符串要好得多):
#包括
...
课堂测试{
...
私人:
std::string str=“123456789”;
};
区别在于
class foo {
class y; // Instance Variable
void foo(){
class x; // Method Variable
// use x and y
}
}
char*
的实例变量将起作用char*x=“foobar”
。编译器可能允许将方法变量设置为char[]
因为范围有限。我试图查找一些文献来解释不同的处理方法。您是在尝试初始化C样式字符串数组?还是要创建一个char*
并将其分配给C字符串?您知道char str[10]=“123456789”错误的代码,Clang:这个代码的错误信息是:“代码>错误:数组绑定不能从类初始化器推断。C++中的这个限制是一个安全特性,这样人们就不会在不实现它的情况下意外地改变类布局。r消息比g++更容易理解。@birryrree我想初始化C字符串。
class foo {
class y; // Instance Variable
void foo(){
class x; // Method Variable
// use x and y
}
}