【发布时间】: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吗? -
当您更改类型时,您是否也删除了
&? -
IMO,最好有
void print(std::ostream& os) const;成员函数,并从operator<<独立函数中将其称为employee.print(os);。
标签: c++ string class operator-overloading ostream