36-经典问题解析三
关于赋值的疑问
【问题】什么时候需要重载赋值操作符?编译器是否提供默认的赋值操作?
- 编译器为每个类默认重载了赋值操作符
- 默认的赋值操作符仅完成浅拷贝
- 当需要进行深拷贝时必须重载赋值操作符
- 赋值操作符与拷贝构造函数有相同的存在意义
【范例代码】默认赋值操作符重载
#include <iostream> #include <string> using namespace std; class Test { int* m_pointer; public: Test() { m_pointer = NULL; } Test(int i) { m_pointer = new int(i); } Test(const Test& obj) { m_pointer = new int(*obj.m_pointer); } Test& operator = (const Test& obj) { if (this != &obj) { 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(int argc, const char* argv[]) { Test t1 = 1; Test t2; t2 = t1; t1.print(); t2.print(); return 0; }