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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值