默认的无参构造和析构函数
不写构造函数时,编译器会默认提供一个无参构造函数
如果显示的提供了一个构造函数,编译器将不再提供无参构造函数
如果显示提供了一个析构函数,编译器将不再提供构造函数
如果手动添加了一个有参构造函数,就需要根据情况添加一个无参构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #define _CRT_SECURE_NO_WARNINGS #include <iostream>
using namespace std;
class Test { public:
Test(int x, int y) { m_x = x; m_y = y; cout << "调用了有参数的构造函数" << endl; }
Test(){ m_x = 0; m_y = 0; cout << "调用了无参数的构造函数" << endl; }
Test(const Test & another) { m_x = another.m_x; m_y = another.m_y; cout << "调用了拷贝构造函数" << endl; }
void operator = (const Test &t) { m_x = t.m_x; m_y = t.m_y; }
void printT() { cout << "x : " << m_x << ", y : " << m_y << endl; }
~Test() { cout << "~Test()析构函数被执行了" << endl; cout << "(" << m_x << ", " << m_y << ")" << "被析构了" << endl; } private: int m_x; int m_y; };
int main(void) { Test t1; Test t2(10, 20); t2.printT(); Test t3(t2); t3.printT();
Test t4(100, 200);
Test t5; t5 = t2;
return 0; }
|