【问题标题】:Regarding const qualifier in C++关于 C++ 中的 const 限定符
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    getarea 不是const,因此不能在const 对象(或const 对其的引用)上调用它。要解决此问题,请将其声明为const

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

    【讨论】: