源代码
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
public:
mystring ()
{
cout << "mystring构造"<<endl;
}
mystring (string const& m_s)
{
s = m_s;
}
~mystring (void)
{
cout << "mystring 析构" <<endl;
};
mystring & operator=(mystring & that)
{
s = that.s;
}
void print()
{
cout << s << endl;
}
private:
string s;
};
class A
{
public:
A()
{
c = new mystring;
cout << "A 构造" <<endl;
cout << "a:"<<c<<"\n";
};
A(A &that)
{
cout << "A拷贝构造" << endl;
c = new mystring;
cout<< "旧的b:"<< c << endl;
c = that.c;
cout << "b:"<< c << "\n" << "a:"<< that.c << endl;
}
/* A & operator=(A &that)
{
*c = *that.c;
return *this;
}*/
~A()
{
cout << "析构的地址:"<< c << "\n";
delete c;
}
private:
mystring *c;
};
class B
{
};
int main ()
{
A a;
A b(a);
return 0;
}
代码里的
A(A &that)
{
cout << "A拷贝构造" << endl;
c = new mystring;
cout<< "旧的b:"<< c << endl;
c = that.c;
cout << "b:"<< c << "\n" << "a:"<< that.c << endl;
}
c = that.c是相当于地址赋值给地址,应该改为*c = *that.c;
还有因为A的成员变量为类成员指针,当A构造或拷贝构造时是不分配内存,需要new一块内存给A的类成员存储数据;
即mystring *c是不分配内存.NULL也是不占内存,即mystring *c = NULL;也是不占空间的,需要new一块内存给它存储.