作者tstanly ()
看板C_and_CPP
标题[问题] copy constructor的问题
时间Mon Mar 16 22:46:52 2009
有点搞不太懂copy construtor的用途
我知道的大概是
物件传给函数时 会复制一个物件
而有可能因为改变此复制物件(ex:delete)时 而改变了原本物件
应该是降对吧...?
以下是一个范例
上面程式码没有使用copy constructor
而下面程式码有
不懂的是为什麽第一个程式码印出
1 2
0 4072544
而加了copy constructor可以解决此问题
我有把output写在程式码下方
谢谢!
=========没有使用copy constructor================
#include <cstdlib>
#include <iostream>
using namespace std;
class myclass{
int *p;
public:
myclass(int i);
~myclass(){ delete p; }
friend int getval(myclass o);
};
myclass::myclass(int i)
{
p=new int;
if(!p){
cout<< "allocation error\n";
exit(1);
}
*p=i;
}
int getval(myclass o)
{
return *o.p;
}
int main(int argc, char *argv[])
{
myclass a(1),b(2);
cout<<getval(a)<<" "<<getval(b);
cout<<"\n";
cout<<getval(a)<<" "<<getval(b);
system("pause");
return 0;
}
output:
1 2
0 4072544
=====================下面是增加一段copy constructor================
#include <cstdlib>
#include <iostream>
using namespace std;
class myclass{
int *p;
public:
myclass(int i);
myclass(const myclass &o); //copy constructor
~myclass(){ delete p; }
friend int getval(myclass o);
};
myclass::myclass(int i)
{
p=new int;
if(!p){
cout<< "allocation error\n";
exit(1);
}
*p=i;
}
//copy construtor
myclass::myclass(const myclass &o)
{
p=new int;
if(!p){
cout<<"allocation error\n";
exit(1);
}
*p=*o.p;
}
int getval(myclass o)
{
return *o.p;
}
int main(int argc, char *argv[])
{
myclass a(1),b(2);
cout<<getval(a)<<" "<<getval(b);
cout<<"\n";
cout<<getval(a)<<" "<<getval(b);
system("pause");
return 0;
}
output:
1 2
1 2
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.116.133.98
1F:推 saxontai:还在加班跟虫虫大军奋战 囧 先给方向:Effective C++ 的 03/16 22:53
2F:→ saxontai:Item 11 03/16 22:53
3F:推 saxontai:啊,抱歉,在 3rd Edition 应该是 Item 14 03/16 23:02
4F:→ tstanly:找机会再来借这本书...XD thanks! 03/16 23:06