我想了解這個複製構造函數問題。在程序退出後,我遇到了與析構函數有關的問題。看來可變char *標題沒有被破壞,我想這可能是錯誤的,謝謝複製構造函數問題
另一個問題是爲什麼當對象x等於x2時不會調用賦值運算符。我使用g ++和codeblocks。
#include <iostream>
using namespace std;
class myClass
{
private:
int x;
int *p;
char* title;
public:
myClass(int tx, int* temp, char* newtitle)
{
x = tx;
cout << "int constructor called with value x = " << x << endl;
p = new int;
p = temp;
title = new char [strlen(newtitle)+1];
strcpy(title, newtitle);
}
myClass(const myClass& mc)
{
cout << "copy constructor called with value = " << mc.x << endl;
x = mc.x;
p = new int;
*p = *mc.p;
title = new char [strlen(mc.title)+1];
strcpy(title, mc.title);
}
myClass & operator = (const myClass & that)
{
cout << "assignment called" << endl;
if(this != &that)
{
x = that.x;
}
return *this;
}
~myClass()
{
if (p)
{
cout<<"deleting p"<<endl;
delete p;
}
else if(title)
{
cout<<"deleting title"<<endl;
delete[] title;
}
}
};
int main()
{
int pointee = 10;
int* p = &pointee;
myClass x(3,p,"hello");
//myClass y = myClass(3,p);
myClass x2 = x;
return 0;
}
修復了您的格式。 – 2010-12-22 17:13:52
也許你需要在析構函數中使用「if(title)」而不是「else if(title)」 – DReJ 2010-12-22 17:15:37