为什么下面定义了强制转换运算符
Why the following defined a cast operator?
>从库中看到了标头定义
operator const wchar_t*() const
任何人都可以向我解释为什么上面定义了铸造操作员?
形式operator typename()
的任何成员函数都是转换函数。
const wchar_t*
是类型名称,因此operator const wchar_t*()
是转换函数。
例如,您希望将一个对象转换为 wchar_t *
,将提供此运算符。
例如
MyString a("hello"); // is a string hold ansi strings. but you want change into wide chars.
wchar* w = (wchar_t*)a; // will invoke the operator~
它是语言的语法。C++允许您创建自己的Operators
例如:
struct A {
bool operator==(const int i);
bool operator==(const char c);
bool operator==(const FOO& f);
}
这允许使用方便地比较我们的类型,哪种语法看起来更好。 A a; if(a == 5) {}
另一种方法是实现一个看起来像A a; if(a.equals(5)) {}
的equals(int value)
方法。
选角也是如此。
struct Angle {
float angle;
operator const float() const {return angle;}
}
Angle theta;
float radius = 1.0f;
float x = radius*cos(theta);
float y = radius*sin(theta);
总之,它只是语言的一个很好的功能,使我们的代码看起来更好,更具可读性。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?