22
A
回答
13
这是一个演员。任何定义此类型的类都可以在需要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&)
。
20
它是一个conversion operator,它允许对象显式或隐式地转换为std :: string。当发生这样的转换时,调用操作符并且转换的结果是调用的结果。
作为隐式转换的示例,假设您有一个接受类型std::string
或const std::string&
的函数,但不包含给定的对象类型。将对象传递给该函数会导致转换运算符被调用,并将结果传递给函数而不是类型。
相关问题
- 1. 运算符bool()转换为std :: string并与运算符冲突std :: string()
- 2. GCC 4.9 std :: string const char *
- 3. C++ const std :: string赋值
- 4. 从“std :: istringstream”初始化“const std :: string”
- 5. 为什么std :: runtime_error :: what()返回const char *而不是std :: string const&
- 6. 在std :: string :: assign(std :: string const&)中的分段错误
- 7. 如何在std :: string中存储const char *?
- 8. 如何在std :: string中存储const char * []?
- 9. 可以CString :: Format()接收const std :: string?
- 10. 错误与转换运算符和的std :: string类中的
- 11. 使用std :: ostream运算符的XOR运算符
- 12. 运算符!=对std :: reverse_iterator不明确C++
- 13. std :: iterator的运算符
- 14. 字符串自动转换为const char *到的std :: string
- 15. C++传递字符串而不是const std :: string&?
- 16. 哪一个使用const char []或const std :: string?
- 17. std :: shared_ptr上的重载运算符==
- 18. 运算符<<和std :: stringstream引用?
- 19. std :: list的重载括号运算符
- 20. const string与#define
- 21. 将'const Link'作为'std :: string'的'this'参数传递给'GetAttribute(std :: string)'丢弃限定符
- 22. 在ostream中使用运算符const char *
- 23. C++:结构,运算符“new”和const
- 24. 运算符+ =重载,为什么是const?
- 25. const char和二元运算符错误
- 26. #define或const string *
- 27. 错误:“对运算符<<(std :: ostream&,Dogs const&)的未定义引用”
- 28. 在std :: function运算符()和std :: forward中发生了什么?
- 29. 运算符在这里重载是什么:String8 :: operator const char *()const
- 30. 用std :: map成员变量的类的下标运算符
我反对术语“永远”,它太绝对了。我认为“通常”会是一个更好的术语。 – 2010-06-15 13:26:57
马丁,我没有说“永远”。我几乎总是说“这不是绝对的”,而且IMO比“通常”更接近真相。 – 2010-06-16 01:48:16
Loki,你自己的评论太绝对了。应该总是避免使用术语“总是”,还是应该避免使用术语“总是”? – Alyoshak 2012-07-25 01:18:31