#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
18.46.重载输出运算符 外部函数方式访问类的公有成员变量
---------------------------------*/
class A
{
public:
A(int x,int y){rx=x;ry=y;}
int rx;
int ry;
};
//operator是进行运算符重载的关键词,要重载的运算符是"<<"
//参数s:代表ostream中对象cout的别名
//参数c:代表类A对象cout的别名
ostream &operator<<(ostream &s,const A&c)
{
s<<c.rx<<'\t';
s<<c.ry<<endl;
return s;
}
void main()
{
A a(3,4),b(5,6);
cout<<a<<b; //由于ostream类没有公有的复制构造函数,
//因此无法调用该类的复制构造函数复制对象
//必须按引用的方式接受ostream的对象,并且按引用的方
//式返回ostream对象
}
运行结果:
3 4
5 6
Press any key to continue
C++ 字符串 17-- 18.46.重载输出运算符 外部函数方式访问类的公有成员变量
最新推荐文章于 2021-06-23 20:55:04 发布