【问题标题】:using static member of a class in .cpp file在 .cpp 文件中使用类的静态成员
【发布时间】:2012-04-02 22:31:55
【问题描述】:

我创建了一个类,并在公共部分中声明了以下内容:

static int num;

在同一个 .h 文件中的构造函数中,我做了:

num++;

到目前为止一切正常。

问题是,我的析构函数的实现是在 .cpp 中,我写道:

num--;

但视觉不允许我这样做。它大喊:

致命错误 LNK1120:1 个未解决的外部问题

有什么帮助吗?

【问题讨论】:

  • 回答您的问题:任何代码?另外:您是否定义(不是声明)该静态成员?你在用什么书吗?

标签: c++ class static fatal-error


【解决方案1】:

您必须在 *.cpp 文件中定义您的静态变量。这通常在顶部完成。例如:

// in the *.h file
class MyClass
{
    public:
        static int num;
        MyClass();
        ~MyClass();
};

// in the *.cpp file
int MyClass::num = 0;

MyClass::MyClass()
{
    MyClass::num++;
}

MyClass::~MyClass()
{
    MyClass::num--;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多