未声明的标识符?我以为我定义了它

时间:2014-01-16 08:42:18

标签: c++ types

所以,我在我的约会课程的成员函数中遇到了未声明的标识符错误,events_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;

}

3 个答案:

答案 0 :(得分:4)

您在Appointment::前面错过了occurs_on

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

答案 1 :(得分:4)

您需要Appointment::前缀:

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

否则你正在定义一个自由函数。

答案 2 :(得分: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;
};

定义内联方法可能对本地类很有帮助,但通常会导致样式不好。