c++ - 错误 : passing ‘const Complex’ as ‘this’ argument of '....' discards qualifiers

标签 c++ compiler-errors operator-overloading overloading operator-keyword

我正在尝试重载 C++ 中的 * 运算符,以复数形式表示。我还在类文件 (Complex.h) 中声明了一个常量 I。 Complex.cpp 是类的实现。主文件用于测试。但是,它无法编译。如何解决?

error: passing ‘const Complex’ as ‘this’ argument of ‘Complex Complex::operator*(const Complex&)’ discards qualifiers [-fpermissive]
 cout << "Actual:" << (I * I) << endl;

这是我的主文件:

#include <iostream>
#include "Complex.cpp"  //remove it 
#include "Complex.h"
using namespace std;
int main (){
    // test multiplication
    cout << "\nExpected:I*I = -1" << endl;
    cout << "Actual:" << (I * I) << endl;
    return 0;
}

这是我的头文件:

#ifndef COMPLEX_H
#define COMPLEX_H
#include <cstdlib> //exit
#include <iostream>

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

    double imag() const{
        return b;
    }
    Complex operator*(const Complex& c2);
    private:
    double a;
    double b;
};

//define a constant i
const Complex I(0,1);
#endif

这是实现文件:

#include "Complex.h"
#include <cmath>

using namespace std;

Complex::Complex(double realNum, double imagNum):a(realNum),b(imagNum){}

Complex::Complex(double realNum):a(realNum),b(0){}

Complex Complex::operator*(const Complex& c2){
    double c = c2.real(), d = c2.imag();
    return Complex((a*c-b*d),(b*c+a*d));
}

最佳答案

你的声明 (I * I) 将两个 const Complex 相乘,这样你只能使用类的 const 方法。但是,您的 operator* 仅在非 const 版本中可用。

要更正,只需将其声明为 const via

Complex operator*(const Complex& c2) const;

实现上也是一样。


编辑:更详细:你基本上有两种可能性来声明一个二元运算符,或者在类之外

Complex operator*(Complex const& a, Complex const& b);

或者在里面通过

Complex operator*(Complex const& a) const;

您选择了类版本。因此,当编译器看到 (I*I) 时,两者都是 const,它会将表达式转换为 I.operator*(I) .但是,为此,operator* 也必须是 const,否则无法从常量 I 中调用它.这是因为编译器必须假定该方法将更改 I,这是不允许的。

关于c++ - 错误 : passing ‘const Complex’ as ‘this’ argument of '....' discards qualifiers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26490113/

相关文章:

C++ 仿函数和列表模板

c++ - 作为 OpenMP pragma 的结果的中间代码

sass - 编译SCSS时我收到一条错误消息,其中指出}

java - 如何使用 TreeMap java?

c++ - 如何用两个参数重载 () 运算符;像(3,5)?

c++ - 了解 Qt View 模型架构 : when to create and how to cleanup indexes in QAbstractItemModel implementation?

c++ - gcc (Linux/MinGW) 是否存在编译器标志以在运行时引发被零除的错误?

ruby - 无法安装rmagick

c++ - 重载 && 和 || 是否真的有原因?不要短路?

c++ - 尝试为枚举重载 operator+= 时出现编译器错误