在C ++中初始化构造函数中的静态成员变量错误
Initializing static member variables in constructors error in c++
我遇到了一个问题,即我在 class 中定义了一个静态成员变量,访问说明符是私有的,但是每当调用对应对象的构造函数时,编译器都会显示错误 "undefined reference to MyObject::count"
这是我的 class 成员变量声明
class MyObject
{ private:
static int count;
public:
MyObject()
{
count=0;
}
};
您必须明确定义 count
,因为没有 count
的定义。您刚刚 声明了 静态变量,您还没有 定义 它。
class MyObject
{ private:
static int count;
MyObject()
{
count=0;
}
};
int MyObject::count = 0; //Explicit definition of static variables.
//This is just declaration of class
class Foo
{
};
//This is definition of class
Foo obj;
当您仅使用第 static int count;
行编译代码时,编译器将找不到静态变量的定义。所以它会给你一个错误 'undefined reference to `MyObject::count'.
解决方案:
class MyObject
{
private:
static int count;
public:
MyObject()
{
count=0;
}
};
int MyObject::count=0;
int main()
{
MyObject obj;
return 0;
}
我遇到了一个问题,即我在 class 中定义了一个静态成员变量,访问说明符是私有的,但是每当调用对应对象的构造函数时,编译器都会显示错误 "undefined reference to MyObject::count" 这是我的 class 成员变量声明
class MyObject
{ private:
static int count;
public:
MyObject()
{
count=0;
}
};
您必须明确定义 count
,因为没有 count
的定义。您刚刚 声明了 静态变量,您还没有 定义 它。
class MyObject
{ private:
static int count;
MyObject()
{
count=0;
}
};
int MyObject::count = 0; //Explicit definition of static variables.
//This is just declaration of class
class Foo
{
};
//This is definition of class
Foo obj;
当您仅使用第 static int count;
行编译代码时,编译器将找不到静态变量的定义。所以它会给你一个错误 'undefined reference to `MyObject::count'.
解决方案:
class MyObject
{
private:
static int count;
public:
MyObject()
{
count=0;
}
};
int MyObject::count=0;
int main()
{
MyObject obj;
return 0;
}