未定义的参考 C++
我有一个名为 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;
并且编译器写入:
对 Student::_avrA 的未定义引用。
你知道为什么会这样吗?
I have a file called Student.h which have the static integers in this way:
class Student
{
public:
static int _avrA,_avrB,_avrC,_avrD;
};
and I have university.h that inherits Student.h .
On the implementation of University.cpp , one of the functions returns:
return (_grade_average*(Student::_avrA/Student::_avrB))+7;
and the compiler writes:
undefined reference to Student::_avrA.
Do you know why it happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已声明这些变量,但尚未定义它们。所以你已经告诉编译器“在某个地方我将有一个具有这个名称的变量,所以当我使用这个名称时,在你到处寻找它的定义之前,不要担心未定义的变量。” 1
在
.cpp
文件中,添加定义:不要在
.h
文件中执行此操作,因为如果您在两个不同的文件中包含两次>.cpp
文件,你会得到多个定义错误,因为链接器将看到多个文件试图创建名为Student::_avrA
、Student::_avbB
等的变量,并根据 一个定义来统治所有规则,这是非法的。1 很像函数原型。在您的代码中,就好像您有一个函数原型但没有主体。
* 因为“在没有显式初始化器的情况下,类的静态整数成员保证被初始化为零”。 (托尼·K)
You have declared those variables, but you haven't defined them. So you've told the compiler "Somewhere I'm going to have a variable with this name, so when I use that name, don't wig out about undefined variables until you've looked everywhere for its definition."1
In a
.cpp
file, add the definitions:Don't do this in a
.h
file because if you include it twice in two different.cpp
files, you'll get multiple definition errors because the linker will see more than one file trying to create a variable namedStudent::_avrA
,Student::_avbB
, etc. and according to the One Definition to Rule Them All rule, that's illegal.1 Much like a function prototype. In your code, it's as if you have a function prototype but no body.
* Because "Static integer members of classes are guaranteed to be initialised to zero in the absence of an explicit initialiser." (TonyK)
您必须定义静态数据成员并声明它们。在您的实现 Student.cpp 中,添加以下定义:
You have to define the static data members as well as declaring them. In your implementation Student.cpp, add the following definitions: