初始化类数据成员的正确位置在哪里?我在头文件中有类声明,如下所示:
foo.h中:
class Foo {
private:
int myInt;
};
Run Code Online (Sandbox Code Playgroud)
然后我尝试在相应的.cpp文件中为myInt设置一个值:
Foo.cpp中:
int Foo::myInt = 1;
Run Code Online (Sandbox Code Playgroud)
我为重新定义myInt而遇到编译器错误.我究竟做错了什么???
Ecl*_*pse 33
你有什么是一个实例变量.该类的每个实例都有自己的myInt副本.初始化它们的地方是在构造函数中:
class Foo {
private:
int myInt;
public:
Foo() : myInt(1) {}
};
Run Code Online (Sandbox Code Playgroud)
类变量是只有一个副本由类的每个实例共享的变量.这些可以在您尝试时初始化.(参见JaredPar对语法的回答)
对于整数值,您还可以选择在类定义中初始化静态const权限:
class Foo {
private:
static const int myInt = 1;
};
Run Code Online (Sandbox Code Playgroud)
这是由无法更改的类的所有实例共享的单个值.
GMa*_*ckG 12
为了扩展Jared的答案,如果你想以现在的方式初始化它,你需要把它放在构造函数中.
class Foo
{
public:
Foo(void) :
myInt(1) // directly construct myInt with 1.
{
}
// works but not preferred:
/*
Foo(void)
{
myInt = 1; // not preferred because myInt is default constructed then assigned
// but with POD types this makes little difference. for consistency
// however, it's best to put it in the initializer list, as above
// Edit, from comment: Also, for const variables and references,
// they must be directly constructed with a valid value, so they
// must be put in the initializer list.
}
*/
private:
int myInt;
};
Run Code Online (Sandbox Code Playgroud)
您正在尝试通过静态初始化构造初始化实例成员。如果您希望这是一个类级变量(静态),则在变量前加上 static 关键字。
class Foo {
private:
static int myInt;
};
Run Code Online (Sandbox Code Playgroud)