将 "const ..." 作为 "this" 参数传递会丢弃限定符 [-fpermissive]

passing "const ..." as "this" argument discards qualifiers [-fpermissive]

我正在编写一个头文件以了解有关 C++ 中运算符重载的更多信息,但在实现两个复数的除法时出现以下错误。

这里是源代码:

#ifndef __COMP_H
#define __COMP_H

#include <iostream>

class Complex{
private:
    double real;
    double imag;

public:
    //constructor
    Complex(double r=0, double i=0){real = r; imag = i;}

    //operator overloading
    Complex operator + (Complex const &obj){
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;

        return res;
    }

    Complex operator - (Complex const &obj){
        Complex res;
        res.real = real - obj.real;
        res.imag = imag - obj.imag;

        return res;
    }

    Complex operator * (Complex const &obj){
        Complex res;
        res.real = real*obj.real + (-1)*imag*obj.imag;
        res.imag = real*obj.imag + imag*obj.real;
        
        return res;
    }

    Complex operator * (double const i){
        Complex res;
        res.real = i*real;
        res.imag = i*imag;

        return res;
    }

    Complex operator / (Complex const &obj){
        Complex conj(obj.real, (-1)*obj.imag);

        Complex res = (*this)*obj; //numerator
        Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value

        res = res*(1/den.real); //multiply it with a scalar value

        return res;
    }

    void print(){
        std::cout << real << " + " << imag << "j\n";
    }
};



#endif

错误如下所示

In file included from main.cpp:2:
comp.h: In member function 'Complex Complex::operator/(const Complex&)':
comp.h:52:27: error: passing 'const Complex' as 'this' argument discards qualifiers [-fpermissive]
         Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value
                           ^~~~
comp.h:32:13: note:   in call to 'Complex Complex::operator*(const Complex&)'
     Complex operator * (Complex const &obj){
             ^~~~~~~~

我在Whosebug上看到了其他答案,但不明白,这个错误是什么意思,如何解决?谢谢!

这个

Complex operator - (Complex const &obj) { ...

等是non-const个成员函数。默认情况下,成员函数是 non-const,这意味着它们被声明为修改 this。您不能在 const 实例上调用它们。大多数运算符不修改 this,因此应声明为 const:

Complex operator - (Complex const &obj) const { ...
                                      // ^^