我有一个名为 Student.h 的文件,它以这种方式包含静态整数:
class Student
{
public:
static int _avrA,_avrB,_avrC,_avrD;
};
我有继承 Student.h 的 university.h。 在 University.cpp 的实现中,其中一个函数返回:
return (_grade_average*(Student::_avrA/Student::_avrB))+7;
然后编译器写道:
undefined reference to Student::_avrA.
你知道为什么会这样吗?
最佳答案
您已经声明了那些变量,但是您还没有定义它们。所以你已经告诉编译器“我将在某个地方使用这个名称的变量,所以当我使用那个名称时,在你到处寻找它的定义之前不要考虑 undefined variable 。” 1
在 .cpp
文件中,添加定义:
int Student::_avrA; // _avrA is now 0*
int Student::_avrB = 1; // _avrB is now 1
int Student::_avrC = 0; // _avrC is now 0
int Student::_avrD = 2; // _avrD is now 2
不要在 .h
文件中这样做,因为如果你在两个不同的 .cpp
文件中两次包含它,你会得到多个定义错误,因为链接器将看到多个文件试图创建名为 Student::_avrA
、Student::_avbB
等的变量,并根据 One Definition to Rule Them All规则,那是非法的。
1 很像函数原型(prototype)。在您的代码中,就好像您有函数原型(prototype)但没有主体。
* 因为“在没有显式初始化器的情况下,类的静态整数成员保证被初始化为零。” (托尼克)
关于c++ - undefined reference C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7332423/