[問題] copy constructor的問題
有點搞不太懂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
推
03/16 22:53, , 1F
03/16 22:53, 1F
→
03/16 22:53, , 2F
03/16 22:53, 2F
推
03/16 23:02, , 3F
03/16 23:02, 3F
→
03/16 23:06, , 4F
03/16 23:06, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章