gpt4 book ai didi

c++ - undefined reference C++

转载 作者:太空狗 更新时间:2023-10-29 23:37:25 25 4
gpt4 key购买 nike

我有一个名为 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::_avrAStudent::_avbB 等的变量,并根据 One Definition to Rule Them All规则,那是非法的。

1 很像函数原型(prototype)。在您的代码中,就好像您有函数原型(prototype)但没有主体。

* 因为“在没有显式初始化器的情况下,类的静态整数成员保证被初始化为零。” (托尼克)

关于c++ - undefined reference C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7332423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com