我想了解这个复制构造函数问题。在程序退出后,我遇到了与析构函数有关的问题。看来可变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