构造函数会在类每次实例化的时候自动调用,构造函数可以分成如下几类:
- 按照是否有参数分为:无参构造函数和有参构造函数,其中无参构造函数也是默认的构造函数
- 按照构造函数的类型分为:普通构造函数和拷贝构造函数
无参构造函数
#include#include using namespace std; class test { public: test() { cout << "test"<< endl; } ~test() {} }; int main(int argc, char const *argv[]) { test t; return 0; }
有参构造函数
#include#include using namespace std; class test { public: test(int value) { cout << "test value: " << value << endl; } ~test() {} }; int main(int argc, char const *argv[]) { test t1(1); test t2 = test(2); test t3 = 3; return 0; }
拷贝构造函数
#include构造函数的规则#include using namespace std; class test { public: test() {} test(const test& t) { m_value = t.m_value; } ~test() {} int m_value; }; int main(int argc, char const *argv[]) { test t; t.m_value = 1; test t1(t); cout << "t1.m_value: "<< t1.m_value << endl; t.m_value = 2; test t2 = test(t); cout << "t2.m_value: " << t2.m_value << endl; t.m_value = 3; test t3 = t; cout << "t3.m_value: " << t3.m_value << endl; return 0; }
- 默认情况下,编译器会为一个类定义三个函数,默认构造函数(无参数,空实现),默认析构函数(无参数,空实现),默认拷贝函数(浅拷贝,对属性值进行拷贝)
- 如果用户定义了有参构造函数,那么编译器将不再定义默认的无参构造函数,但是会提供默认的拷贝函数
- 如果用户定义了拷贝函数,那么编译器将不再提供其他构造函数
默认的拷贝构造函数,是直接进行最简单的赋值拷贝操作,如果出现了指针相关操作的话,会出现因为是简单赋值导致的重复释放的问题。示例如下:
#include析构函数#include using namespace std; class test { public: test(int value, int ptr_value) { m_value = value; m_ptr = new int(ptr_value); } // test(const test& t) { // m_value = t.m_value; // m_ptr = t.m_ptr; // } test(const test& t) { m_value = t.m_value; m_ptr = new int(*t.m_ptr); } ~test() { if (m_ptr != NULL) { delete m_ptr; m_ptr = NULL; } } int m_value; int* m_ptr; }; void func() { test t1(10, 20); test t2(t1); } int main(int argc, char const* argv[]) { func(); return 0; }
析构函数主要进行资源的释放操作,如果类中没有需要手动释放的资源,可以保持空实现。



