0

I have been trying to compile this program but it is giving me an error in regards to overloading the * operator for one of the functions: complex operator *(double n)const

When I try to compile I get the error: no match for 'operator*' in '2 * c'

Here is the header file:

Complex.h

#ifndef COMPLEX0_H
#define COMPLEX0_H

class complex {
    double realNum;
    double imagNum;
public:
    complex();
    complex(double x,double y);
    complex operator *(double n)const;
    complex operator *(const complex &c1)const;
   friend std::istream &operator>>(std::istream &is,complex &cm);
   friend std::ostream &operator<<(std::ostream &os,const complex &cm);
};

#endif

Here is the cpp:

Complex.cpp

 #include "iostream"
#include "complex0.h"

complex::complex() {
    imagNum = 0.0;
    realNum = 0.0;
}

complex::complex(double x, double y) {

    realNum = x;
    imagNum = y;
}

complex complex::operator *(const complex& c1) const{
complex sum;
sum.realNum=realNum*c1.realNum-c1.imagNum*imagNum;
sum.imagNum=realNum*c1.imagNum+imagNum*c1.realNum;
    return sum;
}

complex complex::operator *(double n)const{ 
    complex sum;
    sum.realNum=realNum*n;
    sum.imagNum=imagNum*n;
    return sum;

}
std::istream &operator >>(std::istream& is, complex& cm) {
    is >> cm.realNum>> cm.imagNum;
    return is;
}

std::ostream &operator <<(std::ostream& os, const complex& cm){
os<<"("<<cm.realNum<<","<<cm.imagNum<<"i)"<<"\n";    
return os;
}

main.cpp

#include <iostream>
using namespace std;
#include "complex0.h" 

    int main() {
        complex a(3.0, 4.0); 
        complex c;
        cout << "Enter a complex number (q to quit):\n";
        while (cin >> c) {
            cout << "c is " << c << "\n";
            cout << "a is " << a << "\n";
            cout << "a * c" << a * c << "\n";
            cout << "2 * c" << 2 * c << "\n";
            cout << "Enter a complex number (q to quit):\n";
        }
        cout << "Done!\n";
        return 0;
    }

Can someone explain to me what I have done wrong?

4

2 回答 2

3

成员函数运算符仅适用于第一个操作数属于您的类类型时。如果您想处理第二个操作数属于您的类型的情况,您还需要一个自由函数(在该函数中,我们通过操作的可交换性简单地委托给成员函数):

complex operator*(double n, complex const & x)
{
    return x * n;
}

(请注意标准库已经包含<complex>.)

于 2013-07-17T19:19:20.520 回答
0

您有一个成员函数定义如下:

complex complex::operator *(double n) const;

这将使您可以执行以下操作:complex_number * 3.0,但不是3.0 * complex_number。但是,您不能创建一个可以让您这样做的成员函数3.0 * complex_number。您可以创建该成员函数的唯一位置是在 的定义中double,您无法更改该定义。

不过,除了将其作为成员函数之外,您还可以将其作为独立函数来执行:

complex operator*(complex x, double n); // Called for complex_number * 2.0
complex operator*(double n, complex x); // Called for 2.0 * complex_number
于 2013-07-17T19:23:09.397 回答