【发布时间】:2025-12-31 17:25:06
【问题描述】:
我无法理解为什么它不接受const 限定符的错误
[Error] passing 'const abc' as 'this' argument of 'int abc::getarea()' discards qualifiers [-fpermissive]
这是下面的代码。
#include<iostream>
using namespace std;
class abc{
public:
abc(){
}
abc(int a,int b){
length=a;
height=b;
}
int getarea(){
return length*height;
}
bool operator <(const abc&) const;
private:
int length;
int height;
};
bool abc::operator <(const abc& d) const{
return getarea() < d.getarea();
}
int main(){
abc a(10,12);
abc b(13,15);
if(a < b)
cout << "\n B has larger volume";
else
cout << "\n A has larger volume";
return 0;
}
【问题讨论】:
-
getarea()也必须是const才能将const变量传递给它。 -
谢谢,现在可以使用了。
标签: c++ operator-overloading constants