做一本流行教科书上的题,在结构体中使用成员函数时出现错误:
.../s09-04-02.cpp:30:对“Date::Date(int, int, int)”的未定义引用
// s09-04-02.cpp simple date
#include <iostream>
struct Date {
int y, m, d; // year
Date(int y, int m, int d); // define constructor
void add_day(int n) ; // declare to add n days
int month() {return m;}; // define return month
int day() {return d;}; // define return day
int year() {return y;}; // define return year
};
int main() {
Date birthday {1970,12,30};
std::cout<<birthday.year()<<"\n";
std::cout<<birthday.month()<<"\n";
std::cout<<birthday.day()<<"\n";
}
g++ -g -o s09-04-02 s09-04-02.cpp
/usr/bin/ld: /tmp/ccXgSexK.o: in function `main':
/home/c++/Stroustrup/PPandP2nd/Ch09Classes/s09-04-02.cpp:13: undefined reference to ` Date::Date(int, int, int)'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: d09-04-02] Error 1
很明显,定义了具有匹配名称的函数。为什么当链接器寻找它时它丢失了?
查看了 Stack Exchange 上的几篇文章并...... 包括这篇非常完整(而且很长)的文章 什么是未定义引用未解析的外部符号错误以及如何修复
您已声明
Date
构造函数,因此编译器知道它存在,但您尚未定义(实现)其主体。与add_day()
相同。
您正在调用构造函数,但链接器找不到其实现。