我run了下面這個程式,
/*********************************************/
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class strtype {
char *p;
public:
strtype(char *s);
//strtype(const strtype &o);
~strtype() {delete [] p; cout << "Destructor\n";}
char *get() { return p; }
};
strtype::strtype(char *s) {
int L;
L = strlen(s)+1;
p = new char [L];
if (!p) {
cout<< "Allocate Error\n";
exit(1);
}
cout << "Constructor\n";
strcpy(p, s);
}
void show(strtype x) {
char *s;
s = x.get();
cout << s << "\n";
}
int main() {
strtype a("Hello"), b("There");
show(a);
//show(b);
return 0;
}
/********************************************/
結果每次都會程式異常終止,
後來加上了下面這段程式(copy constructor), 就能正常
/*******************************************/
strtype::strtype(const strtype &o) {
int L;
L = strlen(o.p)+1;
p = new char [L];
if (!p) {
cout<< "Allocate Error\n";
exit(1);
}
cout << "COPY\n";
strcpy(p, o.p);
}
/*******************************************/
我看了書本(Teach Yourself c++)的解釋, 不太能了解
能否請知道的人 就這個程式 說明加入這段code的意義
可以的話, 能否一起介紹copy constructor的其他用意, 並mail到我的信箱.
非常謝謝.
--
※ Origin: 楓橋驛站<bbs.cs.nthu.edu.tw> ◆ From: 210.64.40.132