重载==运算符导致丢弃限定符错误

扇子

我正在使用C ++创建一个复数类。我想重载==运算符。但是我得到了这个错误:

In file included from Complex.cpp:1:0,
             from testComplex.cpp:2:
Complex.h: In function ‘bool operator==(const Complex&, const Complex&)’:
Complex.h:29:21: error: passing ‘const Complex’ as ‘this’ argument of ‘double Complex::real()’ discards qualifiers [-fpermissive]
     return (c1.real() == c2.real() && c1.imag() == c2.imag());

这是我的课程文件:

#ifndef COMPLEX_H
#define COMPLEX_H

class Complex{
    public:
    Complex(void);
    Complex(double a, double b);
    Complex(double a);
    double real(){ 
        return a;
    }

    double imag(){
        return b;
    }
    private:
    double a;
    double b;
};

bool operator==(const Complex& c1, const Complex& c2){
    return (c1.real() == c2.real() && c1.imag() == c2.imag());
}
#endif

如何解决?

纳德

编译器基本上是在说您似乎在使用允许更改只读对象的功能想象一下,如果您可以只读的Complex对象调用成员函数,则您将更改一个只读的对象!IncrementImaginary();

这就是为什么当您的成员函数不更改类的变量(即state)时,您应该const像这样对它们附加一个限定符:

double real() const{
  return a;
}

这样,编译器将知道在类的只读对象上运行此函数是安全的

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章