友元函数实现左移右移操作符重载(函数返回值当左值需返回引用)(进阶2)

    xiaoxiao2026-03-09  6

    cout 的 << 运算符能够输出编译器支持的基础型变量,那么怎么让它根据我们程序员的意愿去输出复杂结构变量呢,这就需要我们去重载 << 运算符了

    #include <iostream> using namespace std; class Complex{//复数类 private: int a; int b; friend void operator << (ostream &, Complex &); public: Complex(int a = 0, int b = 0){ this->a = a; this->b = b; } Complex operator - (Complex &a2){ Complex tmp(this->a - a2.a, this->b - a2.b); return tmp; } }; void operator << (ostream &out, Complex &t){ out << t.a << " + " << t.b << "i" << endl; } int main() { Complex t(1, 2); // cout << t << endl;//(报错)这里要想输出 t 就要进行 “ << ” 运算符重载 ,也就是说 ,你要告诉编译器如何去输出这个对象 // 第一步还是写出原型(承认运算符重载是一个函数) cout.operator<<(t1) // 因为我们无法获得cout的源码(在类中添加成员函数),所以只能通过全局函数,友元地去访问t对象的私有属性 //后面两句效果等同(可以模仿重载加号减号之类) operator << (cout, t); cout << t; return 0; } 确实这样就可以输出了,但是,问题又来了

    当我这样写的时候

    Complex t(1, 2); int c = 100; cout << t << "abc" << c << endl;

    编译器报错了,似乎不支持流式输出了,那可如何是好?

    分析:如果我们返回一个 void  那么就相当于 void.operator<<("abc")  ,编译器自然就报错了

    所以我们只要重载操作符函数返回一个引用就行了 (  也就是将返回 void 变成返回这个对象的自身  )

    比如 cout << t << "abc"    等同于  cout.operator<<(t).operator<<("abc")  先执行 cout.operator<<(t) 然后这个函数的返回值再执行 .operator<<("abc")

    所以我们要改一下,改成这样

    ostream &operator << (ostream &out, Complex &t){// out << t.a << " + " << t.b << "i" << endl; return out; } 同时也千万别忘了 友元函数 声明那边也要对应地修改

    friend ostream &operator << (ostream &out, Complex &t); 好啦,这样就能支持链式输出了

    总结:函数返回值当左值需返回引用,不仅是以上的情况,应该学会举一反三,灵活运用

    转载请注明原文地址: https://ju.6miu.com/read-1307770.html
    最新回复(0)