C ++使用运算符int()代替operator +

耐特

我试图理解为什么operator int()调用而不是定义的operator+

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        D operator+(D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

void main()
{
    cout<<D(1)+D(2)<<"\n";
    system("pause");
}

我的输出是:

int Ctor D
int Ctor D
operator int
operator int
3
D Dtor 2
D Dtor 1
阿伦木

您的表达D(1)+D(2)涉及临时对象。所以你必须改变你的签名operator+const-ref

#include <iostream>
using namespace std;

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        // Take by const - reference
        D operator+(const D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

int main()
{
    cout<<D(1)+D(2)<<"\n";
}

它打印:

int Ctor D 
int Ctor D 
OP + 
int Ctor D
运算符int 
3 
D Dtor 3 
D Dtor 2 
D Dtor 1

operator int同时,找到正确的超负荷打印出来给被调用cout

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章