C++面向对象入门(二十二)重载左移运算符

重载左移运算符以实现输出自定义类型
一般的重载运算符有两种方式
1, 使用成员函数重载
2, 使用全局函数重载
考虑到cout对象应该在左边, 如果使用类的成员函数重载的话, 第一个参数(左边的参数)默认为*this指向的类对象, 在左边不符合要求, 故选择使用全局函数重载运算符
语法:
ostream &operator<<(ostream &cout, const类名 &对象名) {
函数体
}
并且一般的全局函数往往需要访问类对象的私有成员属性, 因此需要在类中声明重载运算符函数为友元函数
语法: friend ostream &operator<<(ostream &cout, const类名 &对象名);
由于cout是ostream类的对象, 且cout对象是单例的, 故应该返回ostream类的引用类型

代码示例:
#include <iostream>
#include <string>

using namespace std;
/**
 * 重载左移运算符以实现输出自定义类型
 * 一般的重载运算符有两种方式
 * 1, 使用成员函数重载
 * 2, 使用全局函数重载
 * 考虑到cout对象应该在左边, 如果使用类的成员函数重载的话, 第一个参数(左边的参数)默认为*this指向的类对象, 在左边不符合要求, 故选择使用全局函数重载运算符
 * 语法:
 * ostream &operator<<(ostream &cout, const类名 &对象名) {
 * 函数体
 * }
 * 并且一般的全局函数往往需要访问类对象的私有成员属性, 因此需要在类中声明重载运算符函数为友元函数
 * 语法: friend ostream &operator<<(ostream &cout, const类名 &对象名);
 * 由于cout是ostream类的对象, 且cout对象是单例的, 故应该返回ostream类的引用类型
 */

class Rider {
    friend ostream &operator<<(ostream &cout, const Rider &rider);
public:
    static string manufacturer;

    Rider() {

    }

    Rider(const string &name, const string &model, const string &driver) : name(name), model(model), driver(driver) {
    }

    ~Rider() {
        cout << model << " UntransForm" << endl;
    }

    Rider(const Rider &rider) {
        cout << "Copy Rider, and Model is " << rider.model << endl;
    }

    Rider &changeModel(const string &model) {
        this->model = model;
        return *this;
    }

    void showModel() const {
        if(this == NULL) {
            return;
        }
        //尝试在常函数中修改成员属性
//        this->name = "零一";
        //error: Cannot assign to non-static data member within const member function 'showModel'
        this->driver = "飞电或人";
        cout << model << endl;
    }

    void showManufacturer() {
        cout << manufacturer << endl;
    }

    /*ostream &operator<<(ostream &cout) const {
        cout << "Rider{name:" << name << ", model:" << model << ", driver:" << driver << "}, produce by " << manufacturer;
        return cout;
    }*/

private:
    string name;
    string model;
    mutable string driver;
};

string Rider::manufacturer = "Toei Tokyo";

ostream &operator<<(ostream &cout,const Rider &rider) {
    cout << "Rider{name:" << rider.name << ", model:" << rider.model << ", driver:" << rider.driver << "}, produce by " << rider.manufacturer;
    return cout;
}

void test1() {
    Rider zeroOne = {"Zero-One","Rising Hopper","Hiden Aruto"};
//    zeroOne << cout;
    cout << zeroOne << endl;
}
int main() {
    test1();
    system("pause");

    return 0;
}

 

 
posted @ 2020-08-20 19:37  DNoSay  阅读(773)  评论(0编辑  收藏  举报