未声明的标识符?我以为我定义了它
Undeclared identifier? I thought I defined it
因此,我在约会类的成员函数中收到未声明的标识符错误,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;
};
内联定义方法可能对本地类有帮助,但通常会导致样式不佳。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- std::带有自定义缓冲区的 iostream 不允许我写入
- 我无法在 qt 的C++代码中定义字符串
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 我希望定义两个具有相同代码的不同名称的库
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 这C++ unordered_map怎么有四个值?我以为这是一个键值对
- 是否需要定义我的退货类型
- 未声明的标识符?我以为我定义了它
- 定义我自己的新操作员
- 定义我自己的复制构造函数
- 0.1 浮点数大于 0.1 双精度.我以为它是假的
- 是否可以通过在单元测试中定义我自己的 PRIVATE 宏来使私有成员公开
- 我应该总是在头文件中定义我的整个模板类吗
- 我应该如何在C++中定义我自己的unsodered_map哈希函数
- 如何输入矩阵样式的txt文件,而不是为C++定义我自己的int 2D数组
- 为什么GCC说main有多个定义?我有一个主
- 多个符号定义,但我只定义我的符号一次