c++ - 重载运算符时出错

标签 c++ class operator-overloading overloading operator-keyword

当我尝试过载运算符“!”时,它给出如下错误。


complex_nums.cpp: In function ‘complex operator!(const complex&)’:
complex_nums.cpp:50:23: error: passing ‘const complex’ as ‘this’ argument discards qualifiers [-fpermissive]
   return complex(c.re(),-c.im());
                       ^
complex_nums.cpp:14:9: note:   in call to ‘double complex::re()’
  double re(){
         ^
complex_nums.cpp:50:31: error: passing ‘const complex’ as ‘this’ argument discards qualifiers [-fpermissive]
   return complex(c.re(),-c.im());
                               ^
complex_nums.cpp:17:9: note:   in call to ‘double complex::im()’
  double im(){
     ^

代码是:


#include<iostream>

class complex{
private:
    double real; //real part of complex
    double imag; // imaginary part of complex
public:
    complex(double r=0., double i=0.):real(r),imag(i){
    }; // constructor with initialization
    complex(const complex&c):real(c.real),imag(c.imag){
    }; // copy constructor with initialization
    ~complex(){
    }; // destructor
    double re(){
        return real;
    }; // read real part
    double im(){
        return imag;
    }; // read imaginary part
    const complex& operator=(const complex&c){
        real=c.real;
        imag=c.imag;
        return *this;
    }; //assignment operator
    const complex& operator+=(const complex&c){
        real += c.real;
        imag += c.imag;
        return *this;
    }; // addition of current complex
    const complex& operator-=(const complex&c){
        real -= c.real;
        imag -= c.imag;
        return *this;
    }; // subtract from current complex
    const complex& operator*=(const complex&c){
        double keepreal = real;
        real = real*c.real-imag*c.imag;
        imag = keepreal*c.imag+imag*c.real;
        return *this;
    }; // multiply current complex with a complex
    const complex& operator/=(double d){
        real /= d;
        imag /= d;
        return *this;
    }; // divide current complex with real
    void print(){
        std::cout<<"Real: "<<re()<<"   Imaginary: "<<im()<<"\n";
    };
    friend complex operator !(const complex& c){
        return complex(c.re(),-c.im());
    };
};

int main(){
    complex C(1.,1.);
    complex P(3.,2.);
    C.print();
    P.print();
    P+=C;
    P.print();
    P=!C;
    P.print();
    return 0;
}

最佳答案

这就是线索......

error: passing ‘const complex’ as ‘this’ argument discards qualifiers

问题是 im()re() 不是常量方法。

关于c++ - 重载运算符时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39292161/

相关文章:

c++ - 静脉端到端延迟

c++ - 返回指向继承类 C++ 的指针

c++ - 为可迭代对象定义模板运算符<<

c++ - 如何使用旧的变换矩阵和坐标获得变换矩阵?

c++ - 一个非常简单的c++ oop问题

C++ 不能使用另一个文件中的类

java - 使用 Point 作为外部类编写内部类

c# - 使用类与结构作为字典键

c++ - 二进制 '+=' : no global operator found which takes type 'Add' C++

c++ - 如何在链表中重载运算符++