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

来源:互联网 发布:wirelessnet是什么网络 编辑:程序博客网 时间:2024/04/29 17:52

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 运算符(形参表)
{
        函数体
}
0 0