C++ 字符串 18-- 18.47.友元的方式重载输出运算符

xiaoxiao2021-02-28  29

#include <iostream> #include <string> using namespace std; /*--------------------------------- 18.47.友元的方式重载输出运算符 ---------------------------------*/ class A { public: A(int x,int y){rx=x;ry=y;} //operator是进行运算符重载的关键词,要重载的运算符是"<<" //参数s:代表ostream中对象cout的别名 //参数c:代表类A对象cout的别名 friend ostream &operator<<(ostream &s,const A&c) { /*******用friend修饰变成类A的友元函数*******/ s<<c.rx<<'\t'; //然后,便可访问类A的私有成员 s<<c.ry<<endl; return s; } private: int rx; int ry; }; void main() { A a(3,4),b(5,6); cout<<a<<b; //由于ostream类没有公有的复制构造函数, //因此无法调用该类的复制构造函数复制对象 //必须按引用的方式接受ostream的对象,并且按引用的方 //式返回ostream对象 } 运行结果: 3 4 5 6 Press any key to continue
转载请注明原文地址: https://www.6miu.com/read-2250084.html

最新回复(0)