每个类除了有普通的构造函数之外,即 Staff(std::string mName,int mAge),还有拷贝构造函数,即 Staff(const Staff &staff)。如下:
Staff.hpp 文件
#includeclass Staff { public: Staff(std::string _name, int _age); Staff(const Staff & staff); ~Staff(); public: std::string name; int age; char * mem = nullptr; };
Staff.cpp 文件
#include "Staff.hpp" #includeStaff::Staff(std::string _name, int _age) { mem = (char *)malloc(20); name = _name; age = _age; printf("构造函数被调用n"); } Staff::Staff(const Staff & staff) { name = staff.name; age = staff.age; mem = (char *)malloc(20); memcpy(mem, staff.mem, 20); } Staff::~Staff() { if(mem != nullptr){ free(mem); mem = nullptr; } printf("析构函数被调用n"); }
main
#include#include "Staff.hpp" int main(int argc,char **argv) { Staff staffA; Staff staffB = staffA; return 0; }
staffB的创建会调用拷贝构造函数,这里在.cpp文件中已经将拷贝构造函数重写了,默认是浅拷贝,也就是说staffB和staffA的mem指针的值相同,二者指向同一块儿地址,如下:



