运算符<<重载ostream

发布于 2024-10-06 05:56:14 字数 265 浏览 8 评论 0 原文

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

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

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

谢谢

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;
}

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我一直都在从未离去 2024-10-13 05:56:14

您不会向 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.

白衬杉格子梦 2024-10-13 05:56:14

仅当它是类的成员函数时才会成为第一个参数。因此,它会是:

class ostream {
    ...
    ostream &operator << (const myClass &o);
    ...
};

由于 ostream 是在您的课程之前很久编写的,因此您会看到将您的课程放在那里的问题。因此,我们必须将运算符实现为独立函数:

(return type) operator << ( (left hand side), (right hand side) );

当运算符实现为类的成员函数时,左侧是 this,参数变为右侧。 (对于二元运算符 - 一元运算符的工作原理类似。)

Only if it is a member function of the class that would otherwise be the first argument. Thus, it would be:

class ostream {
    ...
    ostream &operator << (const myClass &o);
    ...
};

Since ostream was written long before your class, you see the problem of getting your class in there. Thus, we must implement the operator as a freestanding function:

(return type) operator << ( (left hand side), (right hand side) );

When operators are implemented as member-functions of classes, the left hand side is this, and the argument becomes the right hand side. (For binary operators - unary operators work similarly.)

过度放纵 2024-10-13 05:56:14

因为您正在重载自由函数,而不是成员函数。

Because you are overloading a free function, not a member function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文