【问题标题】:"Undefined reference" to declared C++ static member variable [duplicate]对声明的 C++ 静态成员变量的“未定义引用”[重复]
【发布时间】:2016-02-22 23:29:42
【问题描述】:

我已经开始使用 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

给我一​​些中文。

我不明白。

【问题讨论】:

  • Test(double x, std::string) { this-&gt;x=x; this-&gt;name=n; nb=nb+1; } 可以更简洁地写成Test(double x_, std::string name_) : x(x_), name(name_) { ++nb; }。尽可能使用初始化程序以获得胜利和利润。
  • 好问题。使用的代码可能会缩减很多,但要简洁明了。不能对他们进行重复,因为在您知道关键字之前很难用谷歌搜索。

标签: c++ class object methods static


【解决方案1】:

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

int Test::nb;

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

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

【讨论】:

  • 非常感谢,我已经看到了,但无法弄清楚目的,我应该阅读 C struct 以帮助理解。
【解决方案2】:

你的变量static int nb需要初始化,所以你需要在类之后添加一个声明。

class YourClass 
{
    // some stuff
}; //  Your class ends here
int Test::nb = 0;

int main() ...

这里有一些教程和信息tutorial pointcprogramming.com/tutorial/statickeyword

【讨论】:

  • 定义(不是你所说的“声明”)不应该在头文件中(你的答案看起来你建议在类定义之后将它写在头文件中)
  • @M.M 您有权将“定义”放在头文件中。我假设整个示例都写在一个 main.cc 文件中,因为类定义后面是 main 函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2012-11-13
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
相关资源
最近更新 更多