运算符重载为友元函数
郭 炜 刘家瑛
// frend_function.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
using namespace std;
class complexs
{
private:
double real;
double img;
public:
complexs(double i=0,double j=0):real(i),img(j){}
~complexs(){}
void print();
friend complexs operator+(double r,complexs& i);//重载为友元函数,r+complex,友元函数声明
friend complexs operator+(complexs& i,double r);//重载为友元函数,complex+r,友元函数声明
};
void complexs::print()
{
cout<<real<<'+'<<img<<'i'<<endl;
}
complexs operator+(double r,complexs& i)//重加载函数体
{
return complexs(r+i.real,i.img);
}
complexs operator+(complexs& i,double r)//重加载函数体
{
return complexs(r+i.real,i.img);
}
int _tmain(int argc, _TCHAR* argv[])
{
complexs a(2,3);
a.print();
//double b=2;
complexs c;
c=2+a;
c.print();
c=a+2;
c.print();
return 0;
}