vs2017为什么双目运算符重载函数一侧不能用常数,用变量才可以

如果是下面这样
c3 = c1 + 11.0;
cout << "+:\t"; c3.display();
c3 = 11.0 + c2;
cout << "+:\t"; c3.display();
就会报错

这里写图片描述


按上面4.2.cpp
double i = 11;
c3 = c1 + c2;
cout << "+:\t"; c3.display();
c3 = c1 + i;
cout << "+:\t"; c3.display();
c3 = i + c2;
cout << "+:\t"; c3.display();
就可以通过编译。
原因现在不清楚。。。。。
下面是源码。

operator.h
class Complex
{
public:
double real;
double imag;
void display();
Complex(double r, double i) :real(r), imag(i) {}
Complex() { real = 0; imag = 0; }
friend Complex operator +(Complex &, Complex &);
friend Complex operator +(double &, Complex &);
friend Complex operator +(Complex &, double &);
};

operator.cpp
#include<iostream>
#include"operator_+-.h"
using namespace std;
Complex operator +(Complex &a, Complex &b)
{
    return Complex(a.real + b.real, a.imag + b.imag);
}
Complex operator +(double &a, Complex &b)
{
    return Complex(a + b.real, b.imag);
}
Complex operator +(Complex &a, double &b)
{
    return Complex(a.real + b, a.imag);
}
void Complex::display()
{
    cout << "(" << real;
    if (imag >= 0)
        cout << "+";
    cout<< imag << "i)" << endl;
}

4.2.cpp

include

include”operator_+-.h”

using namespace std;
int main()
{
Complex c1(1, 2), c2(3, 2), c3;
double i = 11;
c3 = c1 + c2;
cout << “+:\t”; c3.display();
c3 = c1 + i;
cout << “+:\t”; c3.display();
c3 = i + c2;
cout << “+:\t”; c3.display();
system(“pause”);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值