zoukankan      html  css  js  c++  java
  • 运算符重载

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Complex
     6 {
     7 private:
     8     int a, b;
     9 public:
    10     Complex(int a, int b) :a(a), b(b)
    11     {}
    12 
    13 //      Complex& operator+(Complex &c)          //放在类里
    14 //      {
    15 //          this->a = this->a + c.a;
    16 //          this->b = this->b + c.b;
    17 //          return *this;
    18 //      }
    19 
    20     friend Complex& operator+(Complex &c1, Complex &c2);
    21 };
    22 
    23 Complex& operator+(Complex &c1, Complex &c2)    //放在类外,如果a, b不是类Complex的私有变量的话,是可以不用friend函数来声明重载函数的, 这就是以前在cocos2d-x里学到的全局重载函数
    24 {
    25     Complex c3(1, 1);
    26     c3.a = c1.a + c2.a;
    27     c3.b = c1.b + c2.b;
    28     return c3;
    29 }
    30 
    31 int main()
    32 {
    33     Complex c1(1, 2), c2(3, 4);
    34     Complex c3 = c1 + c2;
    35 
    36     system("pause");
    37     return 0;
    38 }

     两种方式重载

    二元运算符

    全局(友元)   必须有两个参数,分别代表左右操作数

    成员   只能有一个参数代表右操作数,左操作数由this指针隐藏代替,

    一元运算符

    friend Complex operator++(Complex &c1, int);后置++或者--,需要一个占位符与前置区分.

     ----------------------------------------------------------------------

    重载<<只能通过全局函数重载,无法通过成员函数,

    因为这种方式实质上是通过cout.operator<<(c1),必须要在cout这个对象类中添加这个重载方法

    但没有办法拿到cout对象类中的源码,也不可能去改.所以friend函数在这里就起到作用了.

    void operator<<(ostream &cout, Complex &c)
    {
    	cout << "a = " << c.a << "  b = " << c.b << endl;
    }
    
    int main()
    {
    	Complex c1(1, 2), c2(3, 4);
    
    	cout << c1; //cout的类型是ostream
        system("pause"); 
        return 0; 
    }
    

      

      

  • 相关阅读:
    优先队列
    Problem W UVA 662 二十三 Fast Food
    UVA 607 二十二 Scheduling Lectures
    UVA 590 二十一 Always on the run
    UVA 442 二十 Matrix Chain Multiplication
    UVA 437 十九 The Tower of Babylon
    UVA 10254 十八 The Priest Mathematician
    UVA 10453 十七 Make Palindrome
    UVA 10163 十六 Storage Keepers
    UVA 1252 十五 Twenty Questions
  • 原文地址:https://www.cnblogs.com/c-slmax/p/5184013.html
Copyright © 2011-2022 走看看