小编Yur*_*nov的帖子

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

所以我的代码有问题,我想重载运算符<<,所有功能都在抽象类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)

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

c++ string class operator-overloading ostream

-1
推荐指数
1
解决办法
65
查看次数

标签 统计

c++ ×1

class ×1

operator-overloading ×1

ostream ×1

string ×1