【发布时间】:2022-11-15 11:07:45
【问题描述】:
如果我创建一个类:
// First Example
#include <iostream>
#include <string>
class my_class {
std::string str;
public:
my_class(const char* s = "") : str(s) {}
operator const char* () const { return str.data(); } // accessor
};
my_class mc1{"abc"};
std::cout << mc1; // Calls the char* accessor and successfully writes "abc" to screen output.
如果我这样修改类:
// Second Example
class my_class {
std::string str;
public:
my_class(const char* s = "") : str(s) {}
operator std::string () const { return str; } // accessor
};
my_class mc1{"abc"};
std::string mystring = mc1; // Calls the string accessor
std::cout << mystring; // Also successfully writes "abc" to screen output.
但是,如果我尝试调用:
std::cout << mc1;
我会得到一个充满编译错误的页面,开头是:
错误 C2679:二进制“<<”:未找到采用“my_class”类型右手操作数的运算符(或没有可接受的转换)
我可以通过添加到第二个示例类来更正此错误:
friend std::ostream& operator <<(std::ostream& os, my_class& rhs) { os << rhs.str; return os; }我主要抄袭了针对这个问题的建议解决方案之一。但我不明白为什么有必要使用字符串访问器而不是 char* 访问器。
我期望成功编译并输出 mc1.str 的值,或者我会期望在第一个示例中尝试使用 char* 访问器函数时出现相同的错误。相反,我仅在第二个示例中收到了 C2679。
【问题讨论】:
-
你最后一个SN-P的运营商应该是:
friend std::ostream& operator<<(std::ostream& os, const my_class& rhs) { return os << rhs.str; }。暴露的代码与您其余的 sn-ps 不匹配... -
该错误准确地描述了问题。流类没有从
my_class到它理解的东西的转换;流类不知道如何处理my_class。换句话说,流类尚未针对my_class进行编程(很明显)。通过提供一个朋友实施,您明确提供所需的转换。这朋友函数被调用,因为它的参数与语句匹配 -
谢谢@Scheff'sCat 发现了我的复制错误。
标签: c++ string overloading iostream accessor