我正在尝试使用getDate()
调用函数pass by reference
。在函数lessThan()
中,来自object的所有变量都很好,但是在调用对象的函数时出现错误。我为什么要这样做?
错误讯息:
此对象具有与其不兼容的类型限定符 成员函数“CDate :: getDate”对象类型是const CDate
ThisCopyNFriend.h:
#pragma once
#include "Header.h"
class CDate
{
public:
CDate(int, int, int);
~CDate();
void getDate();
bool lessThan(const CDate&);
bool equal(const CDate&);
bool greaterThan(const CDate&);
CDate plus(const CDate&);
CDate operator+(const CDate&);
friend void greet(string);
private:
int day, month, year;
};
ThisCopyNFriend.cpp:
#include "ThisCopyNFriend.h"
CDate::CDate(int _day = 1, int _month = 1, int _year = 1990)
{
this->day = _day;
this->month = _month
;
this->year = _year;
}
CDate::~CDate()
{
}
void CDate::getDate() {
cout << day << "/" << month << "/" << year;
}
bool CDate::lessThan(const CDate &_cdate) {
if (_cdate.year < this->year) {
cout << "\n ";
_cdate.getDate(); // This is the bit that start to have error.
cout << " is less then ";
getDate();
return true;
}
else if(_cdate.month < this->month && _cdate.year == this->year) {
cout << "\n ";
_cdate->getDate();
cout << " is less then ";
getDate();
return true;
}
else if (_cdate.day < this->day && _cdate.month == this->month && _cdate.year == this->year) {
cout << "\n ";
_cdate.getDate();
cout << " is less then ";
getDate();
return true;
}
else {
cout << "\n ";
getDate();
cout << " is less then ";
_cdate.getDate();
return false;
}
}
打开任何有关我的代码的建议!!!
答案 0 :(得分:1)
在C ++中,&#34;限定符&#34;表示const
(或很少,volatile
,但通常不是)。因此,错误消息表示对象为const
,但CDate::getDate
期望非const
对象。要解决这个问题,你应该告诉编译器getDate
实际上没有修改它所调用的对象,只需要void CDate::getDate() const
而不是void CDate::getDate()
。< / p>