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?
complex
on the left side, never a double. – chris