重载运算符<<,os得到一个字符串
Overloading operator << , os gets a string
所以我的代码有问题,我想重载运算符<<,所有函数都在抽象类中 员工所以
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
因此确实是一个更合适的名称。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '