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

Overloading operator << , os gets a string

本文关键字:lt 一个 字符串 运算符 os 重载      更新时间:2023-10-16

所以我的代码有问题,我想重载运算符<<,所有函数都在抽象类中 员工所以

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 只是类中的变量 员工

它只是不起作用,我得到异常 E0317,我理解它就像打印返回它不是字符串一样。另外,如果我将返回类型更改为

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

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

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因此确实是一个更合适的名称。

相关文章: