未定义的参考 C++

发布于 2024-12-03 11:37:54 字数 396 浏览 0 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余生一个溪 2024-12-10 11:37:54

您已声明这些变量,但尚未定义它们。所以你已经告诉编译器“在某个地方我将有一个具有这个名称的变量,所以当我使用这个名称时,在你到处寻找它的定义之前,不要担心未定义的变量。” 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 等的变量,并根据 一个定义来统治所有规则,这是非法的。

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:

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

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 named Student::_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)

难忘№最初的完美 2024-12-10 11:37:54

您必须定义静态数据成员并声明它们。在您的实现 Student.cpp 中,添加以下定义:

int Student::_avrA;
int Student::_avrB;
int Student::_avrC;
int Student::_avrD;

You have to define the static data members as well as declaring them. In your implementation Student.cpp, add the following definitions:

int Student::_avrA;
int Student::_avrB;
int Student::_avrC;
int Student::_avrD;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文