zhiyinjixu

  博客园  :: 首页  ::  :: 联系 ::  :: 管理

运算符重载的两种分类:
一、作为类成员

#include <iostream>
using namespace std;

class complex
{
public:
complex (){}
complex (int x, int y) {real = x; imag = y;}
public:
void display ();
private:
int real;
int imag;
public :
complex operator+ (complex& ob2);
};

complex complex::operator+ (complex& ob2) //以c2为实参调用c1的运算符重载函数
{
complex temp ;
temp.real = real + ob2.real;
temp.imag = imag + ob2.imag;
return temp;
}

void complex::display()
{
cout<<real <<"+"<<imag<<"i";
}



int main ()
{
complex ob1(1,5),ob2(6,5),ob3;
ob3 = ob1 + ob2;
ob3.display();
}



二、作为全局运算符——友元

#include <iostream>
using namespace std;

class complex
{
public:
complex (){}
complex (int x, int y) {real = x; imag = y;}
public:
void display ();
private:
int real;
int imag;
friend complex operator+ (complex& ob1,complex ob2); //运算符重载,作为全局函数——友元
};

void complex::display()
{
cout<<real <<"+"<<imag<<"i";
}

complex operator+ (complex& ob1,complex ob2)
{
complex temp;
temp.real = ob1.real + ob2.real;
temp.imag = ob1.imag + ob2.imag;
return temp;
}


int main ()
{
complex ob1(2,5);
complex ob2(3,8);
complex ob3;
ob3 = ob1 + ob2;
ob3.display();
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



 

 

posted on 2011-11-14 16:06  zhiyinjixu  阅读(232)  评论(0)    收藏  举报