您的位置:首页 > 职场人生

【面向对象程序设计常见面试题】运算符重载的三种方式?(7)

2014-03-28 00:04 357 查看
1、友元函数



class X{

friend 返回类型 operator 运算符(形参数);

}

返回类型 operator 运算符(形参表)

{

函数体

}

#include <iostream>
using namespace std;
class Complex{
public:
Complex(double r=0.0,double i=0.0);
friend Complex operator+ (Complex& a,Complex& b);
friend Complex operator++ (Complex& a);
void show();
private:
double real;
double imag;
};
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
void Complex:: show()
{
cout<<real<<" "<<imag<<endl;
}
Complex operator+ (Complex& a,Complex& b)
{
Complex temp;
temp.real = a.real+b.real;
temp.imag = a.imag+b.imag;
return temp;
}
Complex operator++ (Complex& a)
{
++a.real;
++a.imag;
return a;
}
int main()
{
Complex x1(20,5);
Complex x2(21,5);
Complex x3;
x3 = x1+x2;
x3.show();
+x3;
x3.show();

return 0;
}


2、类成员函数



class X{

返回类型 operator 运算符(形参数);

}

返回类型 class::operator 运算符(形参表)

{

函数体

}

#include <iostream>
using namespace std;
class Complex{
public:
Complex(double r=0.0,double i=0.0);
Complex operator+ (Complex& a);
Complex operator++ ();
void show();
private:
double real;
double imag;
};
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
void Complex:: show()
{
cout<<real<<" "<<imag<<endl;
}
Complex Complex::operator+ (Complex& a)
{
Complex temp;
temp.real = a.real+real;
temp.imag = a.imag+imag;
return temp;
}
Complex Complex::operator++ ()
{
++real;
++imag;
return *this;
}
int main()
{
Complex x1(20,5);
Complex x2(21,5);
Complex x3;
x3 = x1+x2;
x3.show();
+x3;
x3.show();

return 0;
}


class X{

friend 返回类型 operator 运算符(形参数);

}

返回类型 operator 运算符(形参表)

{

函数体

}
class X{

friend 返回类型 operator 运算符(形参数);

}

返回类型 operator 运算符(形参表)

{

函数体

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐