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. “std :: string const”与“const std :: string”
- 2. std :: string + =运算符
- 3. 运算符bool()转换为std :: string并与运算符冲突std :: string()
- 4. 没有运算符==匹配std :: string吗?
- 5. 重载运算符==为const std :: reference_wrapper在std :: unordered_map
- 6. GCC 4.9 std :: string const char *
- 7. C++ const std :: string赋值
- 8. 从“std :: istringstream”初始化“const std :: string”
- 9. 为什么std :: runtime_error :: what()返回const char *而不是std :: string const&
- 10. 在std :: string :: assign(std :: string const&)中的分段错误
- 11. 通过overloading =运算符从std :: string创建字符串对象
- 12. 可以CString :: Format()接收const std :: string?
- 13. 如何在std :: string中存储const char * []?
- 14. 如何在std :: string中存储const char *?
- 15. C++,为什么使用const std :: string&parameterName?
- 16. C++比较为const char *到的std :: string
- 17. 无法将'std :: string'转换为'const char *
- 18. std :: string与静态const的char数组
- 19. std :: string gets(char *)而不是(const char *)
- 20. 改变const的参考std :: string参考
- 21. 使用std :: ostream运算符的XOR运算符
- 22. 如何让MyClass使用std :: string的运算符+
- 23. 错误与转换运算符和的std :: string类中的
- 24. 运算符!=对std :: reverse_iterator不明确C++
- 25. std :: iterator的运算符
- 26. C++传递字符串而不是const std :: string&?
- 27. 字符串自动转换为const char *到的std :: string
- 28. 哪一个使用const char []或const std :: string?
- 29. 从const char * +长度构造一个const std :: string便宜吗?
- 30. 可变模板匹配const和非const的模板std :: string
我反对术语“永远”,它太绝对了。我认为“通常”会是一个更好的术语。 – 2010-06-15 13:26:57
马丁,我没有说“永远”。我几乎总是说“这不是绝对的”,而且IMO比“通常”更接近真相。 – 2010-06-16 01:48:16
Loki,你自己的评论太绝对了。应该总是避免使用术语“总是”,还是应该避免使用术语“总是”? – Alyoshak 2012-07-25 01:18:31