为什么下面定义了强制转换运算符

Why the following defined a cast operator?

本文关键字:转换 运算符 定义 为什么      更新时间:2023-10-16

>从库中看到了标头定义

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);

总之,它只是语言的一个很好的功能,使我们的代码看起来更好,更具可读性。