运算符<<超载ostream [英] operator<< overloading ostream

查看:128
本文介绍了运算符<<超载ostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使用cout,std :: cout<< myObject,为什么我必须传递一个ostream对象?我认为这是一个隐含的参数。

In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.

ostream &operator<<(ostream &out, const myClass &o) {

    out << o.fname << " " << o.lname;
    return out;
}

感谢

推荐答案

您不是向 ostream 添加另一个成员函数,因为这将需要重新定义类。您不能将它添加到 myClass ,因为 ostream 先行。你唯一可以做的是添加一个重载到一个独立的函数,这是你在做的例子。

You aren't adding another member function to ostream, since that would require redefining the class. You can't add it to myClass, since the ostream goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.

这篇关于运算符&lt;&lt;超载ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆