读书人

感觉有意思大家共享解决思路

发布时间: 2012-02-25 10:01:49 作者: rapoo

感觉有意思,大家共享
//例4

//程序作者:管宁
//站点:www.cndev-lab.com
//所有稿件均有版权,如要转载,请务必著名出处和作者

#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();
}
Test operator +(Test& temp2)
{
cout < <this < < "| " < <&temp2 < < "载入加运算符重载函数! " < <endl;
Test result(this-> a+temp2.a);
return result;
}
operator int()
{
cout < <this < < ": " < < "载入转换运算符函数的内存地址: " < <this-> a < <endl;
return Test::a;


}
public:
int a;
};
int main()
{
Test a(100),b(100);
cout < < "a的内存地址: " < <&a < < " | b的内存地址: " < <&b < <endl;
Test c=a+b;
cout < < "c的内存地址: " < <&c < <endl;
cout < <c.a < <endl;
system( "pause ");
}

[解决办法]
在这种情况下,拷贝构造和隐式转换是有优先级的;它的随意性,就好象你在switch中把哪个case放在上面一样,可能编译器的设计者都没有考虑到。这种随意性告诉我们,慎用隐式转换。

我感觉还是拷贝构造优先比较好一些,因为毕竟这是在一个类中。隐式转换在不得不用时才起作用,是比较好的方式。而且后者的可伸缩性不是很好,如果带int的构造函数声明修改了(增加或减少参数,或干脆删除了),使用隐式转换的地方不得不改变语义。
[解决办法]
规范写作
不搞这种复杂的二义

读书人网 >C++

热点推荐