1.拷贝构造函数的定义:
复制构造函数参数为类对象本身的引用,用于根据一个已经存在的对象复制出一个新的该类的对象,一般在函数中会将已经存在对象的数据成员的值复制一份到新的对象中,如果没有写拷贝构造函数,则系统会默认创建一个复制构造函数,当类中有指针成员时,由系统默认创建该构造函数会存在风险。
Stu.h
#ifndef STU_H_ #define STU_H_ class Stu { public: int age; int no; Stu(); ~Stu(); Stu(Stu &r); }; #endif /* STU_H_ */
Stu.cpp
#include "Stu.h" #include <iostream> using namespace std; Stu::Stu() { cout<<"Stu()"<<endl; } Stu::~Stu() { cout<<"~Stu()"<<endl; } //复制构造函数 Stu::Stu(Stu &r) { cout<<"Stu::Stu(Stu &r)"<<endl; this->age = r.age; //此处的this指向当前正在创建的对象stu2,所以 Stu &r=stu1,r指的是stu2,把stu1的值赋给stu2,调用了拷贝构造函数,如果用户没有定义,则系统默认调用系统的拷贝构造函数。 this->no = r.no; }
main.cpp
#include <iostream>
using namespace std;
#include "Stu.h"
#include "Test.h"
void f1() {
Stu stu1;
stu1.age = 100;
stu1.no = 100;
Stu stu2(stu1);//调用复制构造函数
cout<<stu2.age<<endl;//100
cout<<stu2.no<<endl;//100
}
//void f2() {
// Test t1;// t1: *p
// t1.p = (int *)malloc(sizeof(int));
// Test t2(t1);//t2: *p
//}
void f3() {
Test t1( (int *) malloc(sizeof(int)) );
Test t2( (int *) malloc(sizeof(int)) );
Test t3( (int *) malloc(sizeof(int)) );
Test t4(t3);
}
int main() {
f3();
return 0;
}