#include<stdio.h>
#include<iostream>
#include<time.h>
using namespace std;
class Student
{
public:
int age;
Student(const Student &tmpStu)
{
age = tmpStu.age;
cout << "拷贝构造函数被调用" << endl;
}
Student()
{
age = 18;
cout << "构造函数被调用" << endl;
}
};
int main()
{
Student stu;
stu.age = 22;
Student stu1 = stu;
Student stu2(stu);
Student stu3 = (stu);
}
在编辑器角度,编译器会将该语句拆分成两部分
Student stu1;//只是定义了stu1变量,不会调用构造函数
stu.Student::Student(stu);//调用拷贝构造函数,将stu赋值给tmpStu
添加一个函数,里面只有一个return,没有其他功能,并将class类里面加入析构函数,来观察构造函数时如何调用的
void func(Student tmpStu)
{
return;
}
class Student{
public:
int age;
Student(const Student &tmpStu){
age = tmpStu.age;
cout << "拷贝构造函数被调用" << endl;
}
Student(){
age = 18;
cout << "构造函数被调用" << endl;
}
~Student(){
cout << "析构函数被调用" << endl;
}
};
int main()
{
Student stu;
func(stu);
}
运行结果如下
//Student stu;运行这个语句的时候,构造函数被调用
构造函数被调用
//func(stu);运行这个语句的时候,拷贝构造函数被调用
拷贝构造函数被调用
//void func(Student tmpStu),运行完这个函数的时候,析构函数被调用
析构函数被调用
//int main(),运行完main函数以后,析构函数再次被调用
析构函数被调用