重载运算符<<,os得到一个字符串

时间:2019-06-03 18:22:45

标签: c++ string class operator-overloading ostream

所以我的代码有问题,我想重载运算符<<,所有功能都在Employee的抽象类中

friend std::ostream &operator<<(std::ostream &os, const Employee &employee) {
    os<<employee.print();
    return os;
}

这是功能打印:

virtual const std::string& print() const {
   return "description: "+this->description+ " id: "+ std::to_string(this->getID()); }

描述和ID只是Employee类中的一个变量

它只是行不通,并且出现异常E0317,我理解它就像打印返回的不是字符串一样。 另外,如果我将返回类型更改为

std::basic_string<char, std::char_traits<char>, std::allocator<char>>

它神奇地起作用,但是我不明白为什么我不能使用标准字符串。

1 个答案:

答案 0 :(得分:5)

const std::string& print() const

这将返回对临时字符串的引用,该临时字符串在创建后便会超出范围,因此您在函数外部使用的引用无效。

要使其在当前使用该功能的情况下起作用,您需要将其更改为:

const std::string print() const

一个更好的解决方案是也将const放在返回值上,因为对返回的std::string进行更改可能不会影响Employee对象。如果将来的print()函数用户想要std::move返回的字符串或以其他方式对其进行更改,则没有理由尝试来限制它们。

因此,这将是更好的签名:

std::string print() const

正如formerlyknownas_463035818所暗示的那样,此功能实际上与打印没有任何关系。它返回对象的字符串表示形式,因此to_string的确是更合适的名称。