【发布时间】:2011-03-03 22:45:27
【问题描述】:
谁能告诉我具体是什么
operator std::string()
代表什么?
【问题讨论】:
标签: c++ operator-keyword
谁能告诉我具体是什么
operator std::string()
代表什么?
【问题讨论】:
标签: c++ operator-keyword
这是一个conversion operator,它允许将对象显式或隐式转换为std::string。当发生这种转换时,将调用运算符,转换的结果就是调用的结果。
作为隐式转换的示例,假设您有一个接受类型 std::string 或 const std::string& 的函数,但不接受给定的对象类型。将您的对象传递给该函数将导致调用转换运算符,并将结果传递给函数而不是您的类型。
【讨论】:
它是一个强制转换运算符。任何定义此类型的类都可以在需要std::string 的任何地方使用。例如,
class Foo {
public:
operator std::string() const { return "I am a foo!"; }
};
...
Foo foo;
std::cout << foo; // Will print "I am a foo!".
强制转换运算符几乎总是一个坏主意,因为总是有更好的方法来实现相同的结果。在上述情况下,您最好定义operator<<(std::ostream&, const Foo&)。
【讨论】:
error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&& 原因是@ 987654325@ 被定义为模板函数,因此必须对其参数完全匹配,并且隐式转换不相关。