为何会出现Student构造函数的undefined reference错误?
问题:C++初始化Student对象时出现undefined reference错误
编译命令为 g++ main.cpp student.cpp,报错信息:
main.cpp:(.text+0xe): undefined reference to `Student::Student(double)'
涉及代码文件
student.cpp
class Student { private: double gpa; public: Student(double g) : gpa(g) {}; double getGPA() {return gpa;} };
student.h
#ifndef STUDENT_H #define STUDENT_H class Student { private: double gpa; public: Student(double); double getGPA(); }; #endif
main.cpp
#include "student.h" int main() { Student myStudent(4.0); return 0; }
错误原因
你在student.cpp中重新定义了整个Student类,而非实现头文件student.h中声明的类成员函数。这会导致:
- 编译
main.cpp时,编译器依据student.h的声明,生成对Student::Student(double)的调用符号; - 编译
student.cpp时,编译器生成的是另一个独立Student类的构造函数符号(类名相同但属于不同编译单元定义,符号不匹配); - 链接阶段无法找到
student.h中声明的Student::Student(double)实现,因此抛出undefined reference错误。
修正方案
修改student.cpp,不要重新定义类,而是包含头文件并实现声明的成员函数:
修正后的student.cpp:
#include "student.h" // 实现构造函数 Student::Student(double g) : gpa(g) {} // 实现getGPA函数 double Student::getGPA() { return gpa; }
重新执行编译命令 g++ main.cpp student.cpp 即可正常编译链接。
内容的提问来源于stack exchange,提问作者user20278411
相关产品推荐
相关产品推荐

