核心示例代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <iostream>
using namespace std;
class Student
{
public:
Student() {
cout<<"构造函数" << endl;
}
~Student() {
cout << "析构函数" << endl;
}
Student(int width,int ptr) {
cout << "带参构造函数" << endl;
this->width = width;
this->ptr = new int(ptr);
}
Student(const Student &stu) {
cout << "拷贝构造函数" << endl;
this->width = stu.width;
this->ptr = new int(*stu.ptr);
}
void setWidth(int w) {
this->width = w;
}
int getWidth() {
return this->width;
}
void setPtr(int *ptr) {
this->ptr = new int(*ptr);
}
int* getPtr() {
return this->ptr;
}
private:
int width;
int* ptr;
};
Student getStudent(int width, int ptr) {
Student stu(width,ptr);//带参构造
printf("getStudent %p\n",&stu);
return stu;//拷贝构造
//函数结束后stu会被回收走析构函数
}
void main() {
Student *stu1 = new Student();//无参构造
stu1->setWidth(20);
int *p = new int(100);
stu1->setPtr(p);
Student *stu2 = stu1;//指针赋值,创建副本
Student stu3 = *stu1;//指针解引用赋值,深拷贝,会调用拷贝构造函数
cout << "%p:" << stu1 << ", %p:" << stu2 << ",%p:" << &stu3 << endl;
Student stu4 = {20,100};//带参构造
Student stu5 = stu4;//深拷贝,会调用拷贝构造函数
cout << "%p:" << &stu4 << ",%p:" << &stu5<< endl;
Student stu6;//无参构造
stu6 = stu4;//默认调用=赋值操作符
cout << "%p:" << &stu6<<endl;
getStudent(2,3);
getchar();
//整个main结束,getStudent()返回的Student再次被回收,走析构函数
}
运行结果
构造函数
拷贝构造函数
%p:01223508, %p:01223508,%p:00EFFCC0
带参构造函数
拷贝构造函数
%p:00EFFCB0,%p:00EFFCA0
构造函数
%p:00EFFC90
带参构造函数
getStudent 00EFFB54
拷贝构造函数
析构函数
析构函数