预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共23页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

1.构造函数#include<iostream> usingnamespacestd; classPoint{ private:intx,y; public:Point();//构造函数声明 voidprint(){ cout<<"x="<<x<<";"<<"y="<<y<<endl; } }; Point::Point()//构造函数定义 { x=0;y=1;cout<<"Constructiscalled!"<<endl; } voidmain(){ Pointp1;//定义对象并自动调用构造函数 p1.print(); }析构函数是一种用于销毁对象的特殊的成员函数: 1)当一个对象作用域结束时,系统自动调用析构函数; 2)析构函数名字为符号“~”加类名; 3)析构函数没有参数和返回值。 4)一个类中只能定义一个析构函数,析构函数不能重载。 析构函数的作用是进行清除对象,释放内存等。 如同默认构造函数一样,如果一个类没有定义析构函数,编译器会自动生成一个默认析构函数,其格式如下: <类名>::~<默认析构函数名>() { } 默认析构函数是一个空函数。#include<iostream> usingnamespacestd; classPoint{ private:intx,y; public: Point();//构造函数声明 ~Point();//析构函数声明 voidprint(){ cout<<"x="<<x<<";" <<"y="<<y<<endl; } }; Point::Point()//构造函数定义 { x=0;y=1; cout<<"Constructiscalled!" <<endl; } 不带参数的构造函数,其对象的初始化是固定的。要想在建立对象时,传递一定的数据来进行初始化就要引入带参数的构造函数了。如下例: #include<iostream> usingnamespacestd; classPoint{ private:intx,y; public: Point(int,int);//声明带参数的构造函数 voidprint(){ cout<<"x="<<x<<";"<<"y="<<y<<endl; } };Point::Point(intvx,intvy){ x=vx;y=vy;//用传递来的参数对私有变量x,y赋初值 cout<<"Constructiscalled!"<<endl; } voidmain(){ Pointp1(10,10);//定义对象p1,并给构造函数传递实参 p1.print(); } 在构造函数中允许指定函数参数的默认值,这些默认值在函数调用者不确定参数时可以作为参数来使用。对于所有参数都定义了默认值的构造函数,当它被调用时,允许改变传递参数的个数。如下例: #include<iostream> usingnamespacestd; classPoint{ private:intx,y; public: Point(intvx=0,intvy=0);//声明缺省参数的构造函数 voidprint(){ cout<<"x="<<x<<";"<<"y="<<y<<endl; } };Point::Point(intvx,intvy){ x=vx;y=vy;//用传递来的参数对私有变量x,y赋初值 cout<<"Constructiscalled!"<<endl; } voidmain(){ Pointp1(10,10);//传两参数 p1.print(); Pointp2;//不传参数取缺省值 p2.print(); Pointp3(5);//传一个参数,第二个用缺省值 p3.print(); }一个类中可以具有几个构造函数,每个都去适合不同的场合, 这些构造函数靠所带的参数类型或个数的不同来区分,实际上是对 构造函数的重载。如下例: #include<iostream> usingnamespacestd; classPoint{ private:intx,y; public: Point();//声明无参数的构造函数 Point(intvy);//声明带1个参数的构造函数 Point(intvx,intvy);//声明带2个参数的构造函数 voidprint(){ cout<<"x="<<x<<";"<<"y="<<y<<endl; } };Point::Point() {x=0;y=0;cout<<"Construct0iscalled!"<<endl;} Point::Point(intvy) { x=1;y=vy;cout<<"Construct1iscalled!"<<endl;}