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

Yur*_*nov -1 c++ string class operator-overloading ostream

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

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

这是一个函数打印:

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

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

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

std::basic_string<char, std::char_traits<char>, std::allocator<char>>
Run Code Online (Sandbox Code Playgroud)

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

Ted*_*gmo 6

const std::string& print() const

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

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

const std::string print() const

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

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

std::string print() const

正如以前在注释中所暗示的_463035818所暗示的,此功能实际上与打印没有任何关系。它返回对象的字符串表示形式,因此to_string确实是一个更合适的名称。