c ++ compiler to add a function of at least four categories:
- Constructor
- Destructor
- Copy constructor, copies a value of the attribute;
- Assignment operator copies the value of the attribute;
#include <the iostream> the using namespace STD; class the Person { public : the Person ( int Age) { m_Age = new new int (Age); } int * m_Age; ~ the Person () { IF (! m_Age = NULL) { Delete m_Age; m_Age = NULL; } } // herein require the use of references, if not equivalent to the use of a new object copy function the Person & operator = (the Person & P) { // should first determine whether there is in the heap area attributes, if so, to clean and release then deep copy if (m_Age != NULL) { delete m_Age; m_Age = NULL; } m_Age = new int(*p.m_Age); return *this; } }; void test() { Person p1(18); Person p2(20); Person p3(22); p3 = p2 = p1;//赋值操作 cout << "p1的年龄是:" << *p1.m_Age << endl; cout << "p2的年龄是:" << *p2.m_Age << endl; cout << "p3的年龄是:" << *p3.m_Age << endl; } int main() { test(); system("pause"); return 0; }
Output: