2014-01-16 59 views
2

所以,我在我的會員職位,我的約會類,happen_on獲取未聲明的標識符錯誤。我以爲我初始化構造函數中的這些變量和初始化程序列表中的日期對象。但是這兩個變量都不起作用。我只是有點困惑,爲什麼編譯器認爲它是一個未聲明的類型,而不是一個變量。未聲明的標識符?我以爲我定義它

謝謝。

#include<iostream> 
#include <string> 


using namespace std; 

class Date{ 

public: 
    Date(int month, int day, int year); 

    int getMonth() const; 
    int getDay() const; 
    int getYear() const; 

private: 
    int month; 
    int day; 
    int year; 
}; 

Date::Date(int month, int day, int year) { 
    this->month = month; 
    this->day = day; 
    this->year = year; 
} 

int Date::getMonth() const{ 
    return month; 
} 

int Date::getDay() const{ 
    return day; 
} 

int Date::getYear() const{ 
    return year; 
} 


class Appointment 
{ 

    public: 
    Appointment(string description, int month, int day, int year, int hour, int minute); 
    virtual bool occurs_on(int month, int day, int year); 

    private: 
    int hour, minute; 
    string convertInt(int number) const; 
    virtual string print(); 

    protected: 
    Date getDate(); 
    Date date; 


}; 

Appointment::Appointment(string description, int month, int day, int year, int hour, int minute):date(month, day, year){ 
    // the above line, i'm trying to initalize the date object with the three parameters month day and year from the appointment constructor. 
    this-> hour = hour; 
    this-> minute =minute; 

} 

bool occurs_on(int month, int day, int year){ 
    if (date.getMonth()== month && date.getYear()= year && date.getDay()==day) //first error. variables like hour and minute from the constructor and date from the initalizer list are giving me unknown type name errors. I thought I initalized those variables in the constructor and in the initalizer list. 

     day= minute; // 

     return true; 

} 

回答

4

您錯過了occurs_on前面的Appointment::

//---vvvvvvvvvvvvv 
bool Appointment::occurs_on(int month, int day, int year){ 
    // .. 
} 
4

您需要Appointment::前綴:

bool Appointment::occurs_on(int month, int day, int year) 

否則你要定義一個免費的功能。

1

由於在構造函數的定義,這是正確的在你的榜樣,方法名吧,這是你的情況Appointment::之前需要類名前綴每個(外部)方法定義。

另一種選擇是定義方法內嵌,它看起來像這樣

class Appointment 
{ 
    public: 
// ... 
    virtual bool occurs_on(int month, int day, int year){ 
     if (date.getMonth()== month && date.getYear()= year && date.getDay()==day) 
      day= minute; // preparing a next question? ;) 
      return true; // indentation error or even worse? 
    } 
    private: 
    int hour, minute; 
// ... 
    Date date; 
}; 

定義方法直列可能是本地類非常有用,但往往會導致不良作風。