运算符 std::string() const?
有人能告诉我到底
operator std::string()
代表什么吗?
Can somebody tell me what precisely
operator std::string()
stands for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是一个 转换运算符,允许将对象显式或隐式转换为 std ::细绳。当发生此类转换时,将调用该运算符,并且转换的结果就是调用的结果。
作为隐式转换的示例,假设您有一个接受类型
std::string
或const std::string&
的函数,但不接受给定的对象类型。将对象传递给该函数将导致调用转换运算符,并将结果传递给函数而不是您的类型。It is a conversion operator that allows the object to be explicitly or implicitly casted to std::string. When such a cast occurs, the operator is invoked and the result of the cast is the result of the invocation.
As an example of an implicit cast, suppose you had a function that accepted type
std::string
orconst std::string&
, but not the given object type. Passing your object to that function would result in the conversion operator being invoked, with the result passed to the function instead of your type.它是一个强制转换运算符。定义此类型的任何类都可以在需要
std::string
的任何地方使用。例如,Cast 运算符几乎总是一个坏主意,因为总是有更好的方法来实现相同的结果。在上述情况下,您最好定义
operator<<(std::ostream&, const Foo&)
。It is a cast operator. Any class that defines this type can be used anywhere a
std::string
is required. For instance,Cast operators are almost always a bad idea, since there is invariably a better way to achieve the same result. In the above case, you are better off defining
operator<<(std::ostream&, const Foo&)
.