运算符重载

#include <iostream>   
using namespace std;   
   
class Test     
{     
    public
        Test(int a = 0) 
        { 
            cout<<this<<":"<<"载入构造函数!"<<a<<endl; 
            Test::a = a; 
        } 
        Test(Test &temp) 
        { 
            cout<<"载入拷贝构造函数!"<<endl; 
            Test::a = temp.a; 
        } 
        ~Test() 
        { 
            cout<<this<<":"<<"载入析构函数!"<<this->a<<endl; 
            cin.get(); 
        } 
        operator int() 
        { 
            cout<<this<<":"<<"载入转换运算符函数的内存地址:"<<this->a<<endl; 
            return Test::a; 
        } 
    public
    int a; 
}; 
int main() 

    Test a(100),b(100),c; 
    cout<<"a的内存地址"<<&a<<" | b的内存地址"<<&b<<endl; 
    c=Test((int)a+(int)b);//显示式转换 
    //c=a+b;//隐式转换  ,调用构造函数产生临时对象
    cout<<"c的内存地址"<<&c<<endl; 
    cout<<c.a<<endl; 
    system("pause"); 
}
==============

按照C++对无名对象的约定,Test b=Test(99);C++是会按照Test b(99);来处理的,可是由于转换运算符的加入,导致这一规律被破坏,系统会“错误的”认为你是要给对象赋值,所以系统首先利用Test(99)创建一个临时对象用于赋值过程使用,可是恰恰系统又没有使用自动提供的赋值运算重载函数去处理,因为发现b对象并未构造,转而又不得不将开始原本用于赋值而创建的临时对象再次的强转换为int类型,提供给b对象进行构造,可见中间的创建临时对象和载入转换运算符函数的过程完全是多余,读者对此例要认真解读,充分理解。

#include <iostream>   
using namespace std;   
   
class Test     
{     
    public
        Test(int a = 0) 
        { 
            cout<<this<<":"<<"载入构造函数!"<<a<<endl; 
            Test::a = a; 
        } 
        Test(Test &temp) 
        { 
            cout<<"载入拷贝构造函数!"<<endl; 
            Test::a = temp.a; 
        } 
        ~Test() 
        { 
            cout<<this<<":"<<"载入析构函数!"<<this->a<<endl; 
            cin.get(); 
        } 
        operator int()//转换运算符,去掉则不会调用 
        { 
            cout<<this<<":"<<"载入转换运算符函数的内存地址:"<<this->a<<endl; 
            return Test::a; 
        } 
    public
    int a; 
}; 
int main() 

    Test b=Test(99);//注意这里 
    cout<<"b的内存地址"<<&b<<endl; 
    cout<<b.a<<endl; 
    system("pause"); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值