C++重载学习

// 重载学习.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
public:
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
        :a(a), b(b)
    {

    }
    void PrintCom()
    {
        cout << a << "+" << b << "i" << endl;
    }
    // 重载加号运算符
    Complex& operator+(Complex &ComR)
    {
        this->a += ComR.a;
        this->b += ComR.b;
        return *this;
    }
    // 重载前置++
    Complex& operator++()
    {
        ++this->a;
        ++this->b;
        return *this;
    }
    // 重载后置++,设置占位符,用来区别前置与后置
    Complex operator++(int)
    {
        // 先使用,再让cl加加
        Complex tmp = *this;
        ++this->a;
        ++this->b;
        return tmp;
    }
    // 重载左移运算符
    friend ostream& operator<<(ostream& out,Complex &cl)
    {
        return out << cl.a << "+" << cl.b << "i" << endl;
    }
    // 重载右移操作符
    friend istream& operator>>(istream& in, Complex& cl)
    {
        in >> cl.a;
        in >> cl.b;
        return in;
    }
private:
};
int _tmain(int argc, _TCHAR* argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    c1 + c2;
    cin >> c2;
    cout << c1++ << endl << ++c2;
    system("pause");
	return 0;
}

这里解释一下为什么位移运算符必须用友元实现:

因为重载<<或者>> 的时候,本来应该写在ostream或者istream类中,但是编译器不可能允许我们在那里边修改,因此利用友元开一个后门写在我们自己的类中。因此,友元通常用于左右类型不同的运算符重载。注意友元不能重载=, (), [], ->,这四个操作符。

同时要注意,函数返回值当左值,需要返回引用。

猜你喜欢

转载自blog.csdn.net/lasuerte/article/details/80803852