扩大
缩小

构造函数和析构函数

 1 #include<iostream>
 2 using namespace std;
 3 class point 
 4 {
 5 private:
 6     float x,y;
 7 public:
 8     
 9     point(float a=1,float b=1)//缺省构造;
10     {
11         x=a;
12         y=b;
13         cout<<"缺省构造函数point(float a=1,float b=1)已经调用"<<endl;
14     }
15     /*    point()              //缺省构造
16     {
17     x=0;y=0;
18     cout<<"缺省构造函数point()已经调用"<<endl;
19     }
20     */
21     point (point &s)
22     {
23         x=s.x;
24         y=s.y;
25         cout<<"复制构造函数point point (point &s)已经调用"<<endl;
26         
27     }
28     ~point ()        //析构函数;
29     {
30         cout<<"缺省函数已调用"<<endl;
31     }
32     void print()        //输出观察;
33     {
34         cout<<"x="<<x<<" y="<<y<<endl;
35     }
36     
37 };
38 
39 int main()
40 {
41     //point p1;         //编译出错,可以对应point(),也可以point(float a=1,float b=1);产生二义性;
42     point p2(3);       //正确,它对应point(float a=1,float b=1);相当a=3,b=1;
43     // int ok=p2.x;       //错误,私有成员不可调用;
44     
45     p2. print();
46     
47     point p3(p2);       // 正确,调用复制构造函数;
48     p3. print();
49     return 0;
50     
51 }

 

posted on 2012-12-17 17:07  LinuxPanda  阅读(225)  评论(0编辑  收藏  举报

导航