关于赋值的疑问
1、编译器为每个类默认重载了赋值操作符;
2、默认的赋值操作符仅完成了浅拷贝;
3、当需要进行深拷贝时必须重载赋值操作符;
4、赋值操作符与拷贝构造函数有相同的存在意义。
实例分析:
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
int* m_pointer;
public:
Test()
{
m_pointer = NULL;
}
Test(int i)
{
m_pointer = new int(i);
}
void print()
{
cout << "m_pointer = " << hex << m_pointer << endl;
}
~Test()
{
delete m_pointer;
}
};
int main()
{
Test t1 = 1;
Test t2 = t1;
t1.print();
t2.print();
return 0;
}
同一片空间被释放了两次,所以就在运行时出错;
实例分析2;
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
int* m_pointer;
public:
Test()
{
m_pointer = NULL;
}
Test(const Test& obj)
{
m_pointer = new int(*obj.m_pointer);
}
Test(int i)
{
m_pointer = new int(i);
}
Test& operator = (const Test& obj)
{
if(&obj != this)
{
delete m_pointer;
m_pointer = new int(*obj.m_pointer);
}
return *this;
}
void print()
{
cout << "m_pointer = " << hex << m_pointer << endl;
}
~Test()
{
delete m_pointer;
}
};
int main()
{
Test t1 = 1;
Test t2;
t2 = t1;
t1.print();
t2.print();
return 0;
}
进行了重载拷贝构造函数和赋值操作函数;所以在编译运行时没有发生错误;(并且此时两对象的地址是不同的)
一般性原则
1、 重载复制操作符,必然需要实现深拷贝!!!
小结
1、在需要进行深拷贝的时候必须重载赋值操作符;
2、赋值操作符和拷贝构造函数有同等重要的意义;
3、string类通过一个数据空间保存字符数据;
4、string类通过一个成员变量保存当前字符串的长度;
5、C++开关时尽量避开C语言中惯用的编程思想。