gpt4 book ai didi

C++ 运算符重载选项

转载 作者:行者123 更新时间:2023-11-28 02:10:49 25 4
gpt4 key购买 nike

我创建了一个 Date类型,它有 3 个 int 成员 day_ , month_ , 和 year_ .我已经重载了 operator<<对于 Date而且我不知道什么是最佳选择:我目前有一个名为 ostream& showDate(ostream& os) 的函数定义如下:

std::ostream& Date::showDate(std::ostream& os) const {

return os << day_ << '/' << month_ << '/' << year_ << std::endl;
}

operator<<调用它:

std::ostream& operator<<(std::ostream& os, const Date& d) {

return d.showDate(os);
}

但还有另一种选择:

std::ostream& operator<<(std::ostream& os, const Date& d) {

return os << d.getDay() << '/' << d.getMonth() << '/' << d.getYear() << std::endl;
}

最好的选择是什么?

最佳答案

第二个选项是执行此操作的最常见方式,因此可能是最可读的(匹配常见模式)。

它还有一个优点是 Date 类不需要知道任何关于流的信息。 showDate 成员函数在两个类之间引入耦合,否则它们是独立的。

关于C++ 运算符重载选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793308/

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