C++静态变量和函数错误
可能的重复:
拥有是什么意思对静态成员的未定义引用?
我有一个静态类,如下所示:
.h 文件
class c1 {
public:
static int disconnect();
private:
static bool isConnected;
};
.cpp 文件
#include c1.h
int c1::disconnect()
{
c1::isConnected = false;
return 0;
}
但是,当我编译时,出现错误
undefined reference to `c1::m_isConnected'
请帮忙!
Possible Duplicate:
What does it mean to have an undefined reference to a static member?
I have a static class as follows:
.h file
class c1 {
public:
static int disconnect();
private:
static bool isConnected;
};
.cpp file
#include c1.h
int c1::disconnect()
{
c1::isConnected = false;
return 0;
}
However when I compile, there is an error
undefined reference to `c1::m_isConnected'
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须为静态类成员提供实际的对象实例。将以下内容添加到您的 .cpp 文件中:
要将其初始化为特定值,请添加一个初始值设定项:(
顺便说一下,C++ 中的类不能是静态的。类只是类型。只有类成员可以是静止的。)
You have to provide an actual object instance for the static class members. Add the following to your .cpp file:
To initialize it to a specific value, add an initializer:
(By the way, classes in C++ cannot be static. Classes are just types. Only class members can be static.)
isConnected
是一个(非静态)成员变量,如果没有它所属的实例,则无法使用它。虽然静态变量独立于任何对象而存在,但非静态成员变量仅作为该类实例的一部分存在。您需要将
isConnected
设为静态,或者接受将isConnected
设置为false
的c1
实例。你可能想要前者。isConnected
is a (non-static) member variable and you can't use it without an instance that it's a part of. While static variables exist independently of any object, non-static member variables only exist as part of an instance of that class.You need to either make
isConnected
static or accept an instance ofc1
on which to setisConnected
tofalse
. You probably want the former.头文件中的内容是声明。但是,您还需要变量的定义。正确的代码将如下所示:
What you have in header file is declaration. However, you also need a definition of the variable. The correct code will look like this: