类的构造函数、析构函数与赋值函数

类的构造函数、析构函数与赋值函数

构造函数、析构函数与赋值函数是每个类最基本的函数。它们太普通以致让人容易 麻痹大意,其实这些貌似简单的函数就象没有顶盖的下水道那样危险。

每个类只有一个析构函数和一个赋值函数,但可以有多个构造函数(包含一个拷贝 构造函数,其它的称为普通构造函数)。对于任意一个类 A,如果不想编写上述函数, C++编译器将自动为 A 产生四个缺省的函数。

 

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6         //定义date结构
 7     struct date
 8     {
 9        int year;
10        int month;
11        int day;
12     };
13 
14     //定义baby结构
15     struct baby {
16         int    num;
17         float   weight;
18         date   birthday;   // date为结构类型 
19     }; 
20     
21     //声明baby结构变量并初始化
22     baby b1={10001,10,{2002,12,25}};
23 
24     //下列是baby结构变量b1的引用。
25     cout<<"b1.num="<<b1.num<<endl;
26     cout<<"b1.weight="<<b1.weight<<endl;
27     cout<<"b1.birthday.year="<<b1.birthday.year<<endl;
28     cout<<"b1.birthday.month="<<b1.birthday.month<<endl;
29     cout<<"b1.birthday.day="<<b1.birthday.day<<endl;
30     cout<<"--------------------------"<<endl;
31 
32     //声明baby结构变量temp,并进行赋值运算
33     baby temp;
34     temp=b1;
35     cout<<"temp.num="<<temp.num<<endl;
36     cout<<"temp.weight="<<temp.weight<<endl;
37     cout<<"temp.birthday.year="<<temp.birthday.year<<endl;
38     cout<<"temp.birthday.month="<<temp.birthday.month<<endl;
39     cout<<"temp.birthday.day="<<temp.birthday.day<<endl;
40     return 0;
41 }

 

posted @ 2018-08-02 12:54  borter  阅读(316)  评论(0编辑  收藏  举报