C++类默认会有构造函数和析构函数,然后我们用代码去实现一下,以及在什么情况下我们需要去重写构造函数和析构函数
默认的构造函数
1.无参构造
#include <iostream> using namespace std; class test{ public: test(){ cout<<"test的无参构造已经被调用"<<endl; }; private: int m_i; }; int main(){ test temp=test(); }
运行结果如下
当我们删除他,即用delete操作符删除,编辑器就会给我们报错
2.默认拷贝构造函数
// // Created by 18751 on 2023/5/20. // #include <iostream> using namespace std; class test{ public: test(){ cout<<"test的无参构造已经被调用"<<endl; }; test(const test &temp):m_i(temp.m_i){ cout<<"test的拷贝构造已经被调用"<<endl; } private: int m_i; }; int main(){ test temp; test temp2(temp); }
至于为什么是引用传递呢,假如我们用值传递我们可能会有更大的空间开销。不如直接用引用传递节省空间。
3.赋值构造函数
赋值构造函数我们得要知道运算符的重载(是C++多态的一种),因为类不是基本数据类型。我们需要重载运算符才可以对类和类之间使用赋值运算符。
// // Created by 18751 on 2023/5/20. // #include <iostream> using namespace std; class test{ public: test():m_i(0){ cout<<"test的无参构造已经被调用"<<endl; }; test(const test &temp):m_i(temp.m_i){ cout<<"test的拷贝构造已经被调用"<<endl; } test& operator=(const test& other){ if(this==&other){ return *this; } m_i=other.m_i; } private: int m_i; }; int main(){ test temp; test temp2(temp); }