我无法使用默认的复制构造函数。第二行产生错误。
class MyNum
{
private:
int *numPtr;
public:
MyNum( int num)
{
numPtr = new int;
*numPtr = num;
}
~MyNum()
{
delete numPtr;
}
int GetNum()
{
return *numPtr;
}
};
int main()
{
MyNum first( 5 );
MyNum second(first); //error, use default copy constructor
return 0;
}
但是,如果一个类没有分配内存,它可以正常工作。这与" new"?
的使用有关class MyNum
{
private:
int num;
public:
MyNum( int num )
{
this->num = num;
}
~MyNum()
{}
int GetNum()
{
return num;
}
};
int main()
{
MyNum first( 5 );
cout << first.GetNum() << endl;
MyNum second( first );
cout << second.GetNum() << endl;
MyNum third = second;
cout << third.GetNum() << endl;
return 0;
}