【问题标题】:What does the overload "operator X*() const" mean? [duplicate]重载“operator X*() const”是什么意思? [复制]
【发布时间】:2012-09-19 05:52:28
【问题描述】:

可能重复:
what is “operator T*(void)” and when it is invoked?

我们知道下面的代码是重载了*和&操作符

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

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

但我不知道下面的代码是什么意思? (可以通过build)好像是用来获取X的指针的。

operator X*() const
{
    return this;
}

【问题讨论】:

    标签: c++


    【解决方案1】:
    operator X*() const
    {
        return this;
    }
    

    Implicit conversion operator 输入X*。这是用户定义的转换。阅读标准的12.3 了解更多信息。相关Strange way of overloading the dereference operator from a BoostCon talk

    【讨论】:

      【解决方案2】:

      这是所谓的用户定义的转换,即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.
        }
        

      您可以找到更多信息 hereherehere

      【讨论】:

        猜你喜欢
        • 2014-08-20
        • 2020-04-07
        • 2013-03-07
        • 2017-02-01
        • 2015-02-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 2016-07-18
        相关资源
        最近更新 更多