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

Undeclared identifier? I thought I defined it

本文关键字:定义 我以为 标识符 未声明      更新时间:2023-10-16

因此,我在约会类的成员函数中收到未声明的标识符错误,occurs_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;
}

你在occurs_on面前错过了Appointment::

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

Appointment::前缀:

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

否则,您将定义一个自由函数。

与构造函数定义一样,在您的示例中是正确的,每个(外部)方法定义都需要在方法名称之前具有类名前缀,这在您的情况下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;
};

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