“未定义参考";声明C ++静态成员变量 [英] "Undefined reference" to declared C++ static member variable
问题描述
我已经开始使用Java进行编程,我刚刚达到了我认为在语言知识方面的良好"水平.
I have started programming with Java, I just achieved which I consider as a "good" level in matter of language knowledge.
为了娱乐起见,我决定开始使用C ++进行编程,虽然我对这种语言还很陌生,但是我是一个学习速度很快的人,而且我认为它与Java并不太远.
For fun I decided to start programming using C++, I'm fairly new to this language but I'm a fast learner and I think it's not that far from Java.
我创建了一个测试类,该类具有一个值和一个名称作为属性,一个对象计数器作为全局变量.
I've created a test class which has a value and a name as attributes, and an objects counter as a global variable.
#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;
}
执行程序时输出此错误:
When executed the programm outputs this error :
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
变量本质上是围绕全局变量的语法糖.就像全局变量一样,必须在一个完整的源文件中定义,并带有:
In C++, static
variables are essentially syntactic sugar around global variables. Just like global variables, they must be defined in exactly one source file, with:
int Test::nb;
,如果要使用特定值对其进行初始化,
and if you want to initialize it with a particular value,
int Test::nb = 5; // or some other expression
这篇关于“未定义参考";声明C ++静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!