重载操作符* c ++ [英] overloading operator * c++
问题描述
我一直在试图编译这个程序,但它给我一个错误,为重载*运算符的函数之一:复杂运算符*(双n)const
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
当我尝试编译时,我得到错误:在'2 * c'中不匹配'operator *'
When I try to compile I get the error: no match for 'operator*' in '2 * c'
这是头文件:
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
这里是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
$ b
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?
推荐答案
成员函数运算符仅适用于第一个操作数是类类型。如果你想处理第二个操作数是你的类型的情况,你还需要一个自由函数(其中我们简单地通过操作的交换性委托成员函数):
The member function operator only applies when the first operand is of your class type. If you want to handle the case where the second operand is of your type, you need also a free function (in which we simply delegate to the member function by virtue of commutativity of the operation):
complex operator*(double n, complex const & x)
{
return x * n;
}
(请注意,标准库已经包含 ; complex>
)。
(Please note that the standard library already contains <complex>
.)
这篇关于重载操作符* c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!