避免C++隐式类型转换
比如下面的程序,执行 myInt.copy(17); 时,由于找不到匹配的函数,但是有 int 至 MyIntClass 的构造函数,
C++的编译器会进行隐式类型转换,即产生一个临时 MyIntClass 对象,效果如同
MyIntClass *temp = new MyIntClass(17);
myInt.copy(temp);
delete temp;
这样效率不是很好,解决办法是重定义一个支持 int 参数的 copy 成员函数 MyIntClass::copy(int d)
#include
<
iostream
>
using namespace std;
class MyIntClass
{
public :
MyIntClass( int value) :
data(value)
{
}
void copy( const MyIntClass & other)
{
if ( this != & other)
{
this -> data = other.data;
}
}
int getdata()
{
return data;
}
void setdata( int d)
{
data = d;
}
private :
int data;
};
int main()
{
class MyIntClass myInt( 0 );
myInt.copy( 17 );
cout << myInt.getdata() << endl;
return 0 ;
}
using namespace std;
class MyIntClass
{
public :
MyIntClass( int value) :
data(value)
{
}
void copy( const MyIntClass & other)
{
if ( this != & other)
{
this -> data = other.data;
}
}
int getdata()
{
return data;
}
void setdata( int d)
{
data = d;
}
private :
int data;
};
int main()
{
class MyIntClass myInt( 0 );
myInt.copy( 17 );
cout << myInt.getdata() << endl;
return 0 ;
}