c++ - undefined reference C++

标签 c++ linker-errors

我有一个名为 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/

相关文章:

c++ - 在声明为返回unique_ptr <Base>的函数中返回unique_ptr <Derived>

c++ - 令人困惑的 switch 语句行为

c++ - 为什么 c_str() 返回一个 const 指针值时不输出地址

c++ - 在 Linux 上编译一个共享库以面向所有发行版

c++ - 如何在 C++ 中的不同翻译单元之间共享枚举实例?

c++ - 与 OS X 10.10 的链接问题

swift - 在 xcode 7 swift 项目中更新 pod 后出现链接器问题

iphone - 部署目标为 7.0 时架构错误的 undefined symbol

C++ 数组,数组转换不起作用

使用 OpenSSL 的 libcurl 的 Android-21 静态构建