#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");
}