过载"operator X*() const"是什么意思?

What does the overload "operator X*() const" mean?

本文关键字:const 是什么 意思 operator 过载      更新时间:2023-10-16

可能的重复项:
什么是"运算符 T*(void)",何时调用?

正如我们所知,以下代码是重载 * 和 & 运算符

X& operator*() const
{
    return *this;
}
X* operator&() const
{
    return this;
}

但我不知道下面的代码是什么意思?(它可以通过构建)似乎用来获取 X 的指针。

operator X*() const
{
    return this;
}
operator X*() const
{
    return this;
}

Implicit conversion operator键入 X* 。这是用户定义的转换。有关详细信息,请阅读标准12.3。相关 从 BoostCon 谈话中重载取消引用运算符的奇怪方式

这是一种所谓的用户定义转换或UDC。它们允许您通过构造函数或特殊转换函数指定到其他类型的转换。

语法如下所示:

operator <some_type_here>();

因此,您的特定情况是转换为类型X*运算符。

在编写这些代码时,您应该记住一些事项:

  • UDC 不得模棱两可,否则不会被称为
  • 编译器一次只能使用 UDC 隐式转换单个对象,因此链接隐式转换不起作用:

    class A 
    {
        int x;
    public:
        operator int() { return x; };
    };
    class B 
    {
        A y;
    public:
        operator A() { return y; };
    };
    int main () 
    {
        B obj_b;
        int i = obj_b;//will fail, because it requires two implicit conversions: A->B->int
        int j = A(obj_b);//will work, because the A->B conversion is explicit, and only B->int is implicit.
    }
    
  • 派生类中的转换函数不会隐藏基类中的转换函数,除非它们转换为相同的类型。

  • 通过构造器进行转换时,只能使用默认转换。例如:

    class A
    {
        A(){}
        A(int){}
    }
    int main()
    {
        A obj1 = 15.6;//will work, because float->int is a standart conversion
        A obj2 = "Hello world!";//will not work, you'll have to define a cunstructor that takes a string.
    }
    

您可以在此处、此处或此处找到更多信息。