C++静态变量和函数错误

发布于 2024-12-04 05:05:35 字数 607 浏览 0 评论 0原文

可能的重复:
拥有是什么意思对静态成员的未定义引用?

我有一个静态类,如下所示:

.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十二 2024-12-11 05:05:35

您必须为静态类成员提供实际的对象实例。将以下内容添加到您的 .cpp 文件中:

 bool c1::isConnected;

要将其初始化为特定值,请添加一个初始值设定项:(

 bool c1::isConnected = false;

顺便说一下,C++ 中的类不能是静态的。类只是类型。只有类成员可以是静止的。)

You have to provide an actual object instance for the static class members. Add the following to your .cpp file:

 bool c1::isConnected;

To initialize it to a specific value, add an initializer:

 bool c1::isConnected = false;

(By the way, classes in C++ cannot be static. Classes are just types. Only class members can be static.)

嘦怹 2024-12-11 05:05:35

isConnected 是一个(非静态)成员变量,如果没有它所属的实例,则无法使用它。虽然静态变量独立于任何对象而存在,但非静态成员变量作为该类实例的一部分存在。

您需要将 isConnected 设为静态,或者接受将 isConnected 设置为 falsec1 实例。你可能想要前者。

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 of c1 on which to set isConnected to false. You probably want the former.

橘虞初梦 2024-12-11 05:05:35

头文件中的内容是声明。但是,您还需要变量的定义。正确的代码将如下所示:

class c1 {
public:
    static int disconnect();
private:
    static bool isConnected;
};

bool c1::isConnected = false;

int c1::disconnect()
{
    isConnected = false;
    return 0;
}

What you have in header file is declaration. However, you also need a definition of the variable. The correct code will look like this:

class c1 {
public:
    static int disconnect();
private:
    static bool isConnected;
};

bool c1::isConnected = false;

int c1::disconnect()
{
    isConnected = false;
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文