c/c++ 友元的简单应用

友元的简单应用

1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了,

因为编译器会把数字 + 对象翻译成数字.operator+(const 类 &对象),因为数字不是类的对象,无法传递给类的成员函数this指针。

用友元去重载:数字 + 对象

2,用友元去重载:>>运算符和<<运算符

其实用类的成员函数也可以重载<<运算符,但是使用起来比较怪异,不能使用cout << 对象,只能使用对象 << cout。

#include <iostream>
using namespace std;

class Imaginary{
  friend Imaginary operator+(int i, const Imaginary &m);
  friend ostream& operator<<(ostream &os, const Imaginary &m);
  friend istream& operator>>(istream &is, Imaginary &m);
public:
  Imaginary():real(0), imag(0){
    cout << "c:" << this << endl;
  }
  Imaginary(int real, int imag):real(real), imag(imag){
    cout << "c:" << this << endl;
  }
  Imaginary operator+ (const Imaginary &m){
    return Imaginary (real + m.real, imag + m.imag);
  }
  Imaginary operator+ (int i){
    return Imaginary(real + i, imag);
  }
  Imaginary& operator= (const Imaginary &m){
    cout << "asign" << endl;
    if(this != &m){
      real = m.real;
      imag = m.imag;
    }
    return *this;
  }
 ostream& operator<<(ostream& os){
    os <<  "[" << real << "," << imag << "]";
    return os;
  }
  ~Imaginary(){
    cout << this << endl;
  }
private:
  int real;
  int imag;
};
Imaginary operator+(int i, const Imaginary &m){
  return Imaginary(i + m.real, m.imag);
}

ostream& operator<<(ostream &os, const Imaginary &m){
  os <<  "(" << m.real << "," << m.imag << ")";
  return os;
}
istream& operator>>(istream &is, Imaginary &m){
  is >> m.real >> m.imag;
  return is;
}
int main(){
  Imaginary m1(10, 20);
  Imaginary m2(1, 2);
  Imaginary m3 = m1 + m2;
  Imaginary m4 = m1 + 10;
  Imaginary m5 = 20 + m1;
  cout << "a" << m5 << "aa" << endl;;
  m5 << cout << "bb" << endl;
  Imaginary m6;
  cin >> m6;
  cout << m6 << endl;
  return 0;
}
posted @ 2018-08-20 10:19  小石王  阅读(542)  评论(0编辑  收藏  举报