#include<iostream>
using namespace std;
class Date
{
public:
Date(int ,int ,int );
void show();
~Date();
private:
int year;
int month;
int day;
};
Date::Date(int y,int m,int d):year(y),month(m),day(d){cout<<"我是日期类的构造函数"<<endl;};
void Date::show()
{
cout<<"my birthday is"<<year<<" "<<month<<" ."<<day<<endl;
}
Date::~Date()
{
cout<<"我是 date 类的析构函数"<<endl;
}
class ID
{
public:
ID(int);
int getid();
~ID();
private:
int id;
};
ID::ID(int i):id(i){cout<<"我是id类的构造函数"<<id<<endl;};
ID::~ID()
{
cout<<"我是 id类的析构函数 "<<endl;
}
class Student
{
public:
Student(string ,char ,int ,ID,Date );
void show();
~Student();
private:
string name;
char sex;
int age;
Date date;
ID id;
};
Student::~Student()
{
cout<<"我是学生类的析构函数"<<endl;
}
Student::Student(string n,char s,int a,ID i,Date d):id(i),date(d),name(n),sex(s),age(a){cout<<"我是学生类的构造函数"<<endl;};
int main()
{
Date da(1999,8,13);
Student stu1("dwz",'g',19,12,da); //12传进去会调用构造函数,会生成一个副本,stu1执行完以后会调用析构函数销毁
return 0; //da传进去也会生成副本,调用系统默认的拷贝构造函数,也会生成副本,所以除了Student这个类的定义,就会执行销毁,所以前后一共有要执行6次析构函数
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019072921283975.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDA3NzE3MA==,size_16,color_FFFFFF,t_70)
****************************************************************************************************************************************************
#include<iostream>
using namespace std;
class Date
{
public:
Date(int ,int ,int );
void show();
Date(Date &);
~Date();
private:
int year;
int month;
int day;
};
Date::Date(int y,int m,int d):year(y),month(m),day(d){cout<<"我是日期类的构造函数"<<endl;};
void Date::show()
{
cout<<"my birthday is"<<year<<" "<<month<<" ."<<day<<endl;
}
Date::~Date()
{
cout<<"我是 date 类的析构函数"<<endl;
}
Date::Date(Date &t)
{
year=t.year;
month=t.month;
day=t.day;
}
class ID
{
public:
ID(int);
int getid();
~ID();
private:
int id;
};
int ID::getid()
{
return id;
}
ID::ID(int i):id(i){cout<<"我是id类的构造函数"<<id<<endl;};
ID::~ID()
{
cout<<"我是 id类的析构函数 "<<endl;
}
class Student
{
public:
Student(string ,char ,int ,ID,Date &);
void show();
~Student();
private:
string name;
char sex;
int age;
Date date;
ID id;
};
void Student::show()
{
cout<<"my name is "<<name<<endl;
cout<<"i'm "<<age<<"years old this year"<<endl;
cout<<"my id is"<<id.getid()<<endl;
date.show();
}
Student::~Student()
{
cout<<"我是学生类的析构函数"<<endl;
}
Student::Student(string n,char s,int a,ID i,Date &d):id(i),date(d),name(n),sex(s),age(a){cout<<"我是学生类的构造函数"<<endl;};
int main()
{
Date da(1999,8,13);
Student stu1("dwz",'g',19,12,da);//da传进去的是引用,所以不会产生副本,但是12传进去会调用构造函数,会产生副本,所以前后一共5此析构
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019072921280081.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDA3NzE3MA==,size_16,color_FFFFFF,t_70)
至于为什么会先调用 id的析构函数,我明明是先构造id的,这个应该是后析构,楼主和别人讨论猜测是
构造顺序应该是未定义的
这就类似你函数调用时 同时在好几个参数写了 i++一样 求值顺序应该是未定义的
纯猜测
析构函数的一些细节
最新推荐文章于 2024-09-30 07:31:33 发布