2012-08-16 79 views
1

我很喜欢这个例子。根据教科书,一切都很好。无法编译简单的C++程序,需要澄清

然而,试图编译这些文件时,我得到一个问题(见下文)

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而不是,程序失败。

这是怎么回事?

回答

3

您还没有为您的课程提供setDate方法。您在头文件中声明它,但您也需要为其提供实际的代码

你看到的错误是告诉你的是,连接器(ld),虽然你有一段代码试图呼叫该方法中,连接器不知道它在哪里。

您需要提供的方法,如把以下内容Date.cpp

void Date::setDate (int month, int day, int year) { 
    m_month = month; 
    m_day = day; 
    m_year = year; 
} 
2

你的关心从两个构造函数调用该函数的setDate是不确定的

你需要的东西就像在你的.cpp文件

void Date::setDate(int month, int day, int year) 
     { 
      //code 
     } 
2

看来,你从来没有定义Date::setDate()

+0

叹了口气..我这么傻。谢谢 – 2012-08-16 04:12:00

+0

不用担心。这就是你学习的方式 – lol 2012-08-16 04:13:41