我从我正在阅读的材料中借鉴了这个例子。根据教科书,这里一切都很好。
然而,当试图编译这些文件时,我遇到了一个问题(见下文)
3 个文件
Date.cpp:
#include "Date.h"
Date::Date()
{
setDate(1,1,1900);
}
Date::Date(int month, int day, int year)
{
setDate(month, day, year);
}
Date.h:
class Date
{
public:
Date ();
Date (int month, int day, int year);
void setDate(int month, int day, int year);
private:
int m_month;
int m_day;
int m_year;
};
Main.cpp:
#include "Date.h"
int main ()
{
Date d1 ;
return 1;
}
尝试编译时g++ *
,我得到
Undefined symbols for architecture x86_64:
"Date::setDate(int, int, int)", referenced from:
Date::Date() in cc8C1q6q.o
Date::Date() in cc8C1q6q.o
Date::Date(int, int, int) in cc8C1q6q.o
Date::Date(int, int, int) in cc8C1q6q.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
当我Date *d;
改为声明时,程序编译。当我Date *d = new Date
改为声明时,程序失败。
请问这里是怎么回事?