C++中调用const引用对象成员函数报错原因咨询
错误原因详解
你遇到的这个错误其实是C++里const限定符的典型坑!先看错误提示:
This object has type qualifiers that are not compatible with the member function "CDate::getDate" object type is const CDate
核心逻辑是:被const修饰的对象,只能调用同样被声明为const的成员函数。在lessThan()函数里,参数_cdate是const CDate&类型——这意味着这个引用指向的对象是被const保护的,编译器会确保它的状态不会被修改。但你的getDate()成员函数没有标记为const,编译器默认认为它可能会修改对象的成员变量,所以直接拒绝了const对象调用它的请求。
另外,代码里还有个小语法错误:_cdate->getDate()这行,_cdate是引用类型不是指针,得用.运算符调用成员函数,应该写成_cdate.getDate()。
代码优化建议
我给你整理了具体的修改方案,分点说明:
1. 把getDate()声明为const成员函数
因为getDate()只是输出日期数据,完全不会修改任何成员变量,所以必须给它加上const修饰,这样const对象就能正常调用它了:
- 修改头文件
ThisCopyNFriend.h里的函数声明:
void getDate() const; // 末尾添加const
- 修改cpp文件
ThisCopyNFriend.cpp里的函数定义:
void CDate::getDate() const { // 同样添加const cout << day << "/" << month << "/" << year; }
2. 修复引用调用的语法错误
把lessThan()函数里的_cdate->getDate()改成_cdate.getDate(),引用类型必须用.访问成员,->是指针专用的运算符。
3. 简化lessThan()逻辑,减少冗余代码
你现在的函数里重复了大量cout代码,可以先判断出日期大小关系,再统一输出,让代码更简洁易读:
bool CDate::lessThan(const CDate &_cdate) { // 按年→月→日的顺序比较 if (_cdate.year != this->year) { bool isLess = _cdate.year < this->year; cout << "\n "; _cdate.getDate(); cout << (isLess ? " is less than " : " is greater than "); this->getDate(); return isLess; } if (_cdate.month != this->month) { bool isLess = _cdate.month < this->month; cout << "\n "; _cdate.getDate(); cout << (isLess ? " is less than " : " is greater than "); this->getDate(); return isLess; } bool isLess = _cdate.day < this->day; cout << "\n "; _cdate.getDate(); cout << (isLess ? " is less than " : " is greater than "); this->getDate(); return isLess; }
4. 用初始化列表优化构造函数
C++里用初始化列表初始化成员变量,比在构造函数体内赋值更高效,也更符合编码规范:
CDate::CDate(int _day = 1, int _month = 1, int _year = 1990) : day(_day), month(_month), year(_year) { // 这里不需要再写赋值语句了 }
内容的提问来源于stack exchange,提问作者FMT_WL

