1

我从我正在阅读的材料中借鉴了这个例子。根据教科书,这里一切都很好。

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

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改为声明时,程序失败。

请问这里是怎么回事?

4

3 回答 3

3

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

您看到的错误是链接器 ( ld) 告诉您,尽管您有一段代码试图调用该方法,但链接器不知道它在哪里。

您需要提供方法,例如将以下内容放入Date.cpp

void Date::setDate (int month, int day, int year) {
    m_month = month;
    m_day = day;
    m_year = year;
}
于 2012-08-16T04:07:53.890 回答
2

您关心从两个构造函数调用的函数 setDate 未定义

您需要类似 .cpp 文件中的内容

  void  Date::setDate(int month, int day, int year)
        {
            //code
        }
于 2012-08-16T04:08:27.243 回答
2

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

于 2012-08-16T04:08:27.713 回答