gpt4 book ai didi

c++ - 了解 ostream 重载

转载 作者:行者123 更新时间:2023-11-28 06:36:39 27 4
gpt4 key购买 nike

我无法理解在重载类的 ostream 方法时收到的错误。

class.cpp 中的代码

ostream& operator<<(ostream& out, const dateType& d)
{
out << d.getYear() << "-" << d.getMonth() << "-" << d.getDay()
return out;
}

我知道所有三个 getter 都有效,请在我的 main.cpp 中测试它们。

但是,当我运行类似的东西时:

cout << d1 << endl:

我收到这个错误:

‘std::ostream& dateType::operator<<(std::ostream&, dateType&)’ must take exactly one argument
ostream& operator<<(ostream&, dateType&);

我为另一个运行良好的程序编写了这样的 ostream 代码。那么,为什么我会在此处收到错误消息?

最佳答案

你把它写成 dateType 的成员函数, 和成员 operator<<可能只接受一个显式参数(因为第一个是隐式的并且运算符是二元的)。目前你有一种三参数 operator<< , 取隐式 dateType , 然后 std::ostream& , 然后是另一个 dateType !

这是成员(member)的方式operator<<看起来:

struct T
{
operator<<(ostream&);
};

问题是现在你有一个 operator<<这需要 T 左边 和右边的流,这与惯例相反。 T() << std::cout不对吧?

通常,我们为我们的 operator<< 使用命名空间范围重载,我们可以完全控制参数顺序。

也就是说,不要让它成为dateType的成员函数.
您可能需要将此新功能设为 frienddateType如果这些 setter/getter 是 private .


I wrote an ostream code like this for another program that works fine.

不,你/它没有。

关于c++ - 了解 ostream 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26673449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com