c++ - "Undefined reference"声明的 C++ 静态成员变量

标签 c++ class object methods static

<分区>

我已经开始使用 Java 进行编程,我刚刚达到了我认为在语言知识方面“良好”的水平。

为了好玩,我决定开始使用 C++ 进行编程,我对这门语言相当陌生,但我学得很快,而且我认为它与 Java 相差不远。

我创建了一个测试类,它有一个值和一个名称作为属性,一个对象计数器作为全局变量。

 #include<iostream>


/* local variable is same as a member's name */
class Test
{
    private:
       double x;
       std::string name;
       static int nb;
    public:
        Test(double x, std::string n)
        {
            this->x=x;
            this->name=n;
            nb=nb+1;
        }
       void setX (double x)
       {
           // The 'this' pointer is used to retrieve the object's x
           // hidden by the local variable 'x'
           this->x = x;
       }
       double getX()
       {
           return this->x;
       }
       std::string getName()
       {
           return this->name;
       }

       static int getNb()
       {
           return nb;
       }

};


int main()
{
   Test obj(3.141618, "Pi");
   std::cout<<obj.getX()<<" "<<obj.getName()<<" "<<Test::getNb()<<std::endl;
   return 0;
}

当程序执行时输出这个错误:

In function `Test::Test(double, std::string)':
 (.text._ZN4TestC2EdSs[_ZN4TestC5EdSs]+0x4a): undefined reference to `Test::nb'
 (.text._ZN4TestC2EdSs[_ZN4TestC5EdSs]+0x53): undefined reference to `Test::nb'
In function `Test::getNb()':
 (.text._ZN4Test5getNbEv[_ZN4Test5getNbEv]+0x6): undefined reference to `Test::nb'
error: ld returned 1 exit status

给我一​​些中文。

我不明白。

最佳答案

在 C++ 中,static 变量本质上是围绕全局变量的语法糖。就像全局变量一样,它们必须在同一个源文件中定义,具有:

int Test::nb;

如果你想用一个特定的值来初始化它,

int Test::nb = 5; // or some other expression

关于c++ - "Undefined reference"声明的 C++ 静态成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565971/

相关文章:

c++ - Qt C++ xor 用于校验和?

c++ - Winpcap 开发人员在 Cygwin C++ 和 Netbeans IDE 中的使用

c++ - Qt 调试器输入不工作

javascript - 如何将目标 =“_blank” 添加到具有特定类名的 div 内的链接?

javascript - 在 JavaScript 中使原始数据类型只读/非配置

c++ - 编译时 OpenGL GLI 错误

c# - C# 中的方法与属性 - 有什么区别

jquery - 仅更改在多个类之间单击的类具有相同名称的样式

c++ - 对象作为成员变量

javascript - JSON - 如果对象的值等于