运算符重载的两种分类:
一、作为类成员
#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();
}
浙公网安备 33010602011771号