【问题标题】:Overloading operator << , os gets a string重载运算符 << , os 得到一个字符串
【发布时间】:2019-10-19 07:41:22
【问题描述】:

所以我的代码有问题,我想重载运算符

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,我理解它就像 print 返回它不是一个字符串。 另外,如果我将返回类型更改为

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

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

【问题讨论】:

  • 请包含minimal reproducible example,即如果“没关系”,则将其从示例中删除,但添加足够的内容以便编译并重现问题
  • 不是问题,但你不认为你的print 应该被称为to_string吗?
  • 当您更改类型时,您是否也删除了&amp;
  • IMO,最好有void print(std::ostream&amp; os) const; 成员函数,并从operator&lt;&lt; 独立函数中将其称为employee.print(os);

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


【解决方案1】:

const std::string&amp; print() const

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

要让它在你当前使用该功能的情况下工作,你需要将其更改为:

const std::string print() const

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

所以,这将是一个更好的签名:

std::string print() const

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    相关资源
    最近更新 更多