关于c++中的const限定符

Regarding const qualifier in C++

本文关键字:const c++ 中的 关于      更新时间:2023-10-16

我无法理解为什么不接受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;
     }  

int abc::getarea()未标记为const,但它正在从其const成员函数之一的const对象上调用。您应该将getarea成员函数标记为const,因为它不会改变对象的状态。

getarea不是const,所以它不能在const对象(或const引用)上调用。要解决这个问题,请将其声明为const:

int getarea() const {
    //        ^^^^^
    return length*height;
}