4.2.4 重载构造函数与拷贝构造函数
C++(www.cppentry.com)允许重载构造函数,所谓的重载构造函数是指允许在类中有多个构造函数。当然这些构造函数肯定是有区别的。各个构造函数必须拥有不同的参数个数或者参数类型。
【示例4.14】 定义类classexample有3个构造函数,代码如下所示。
- class classexample
- {
- public:
- classexample();
- classexample(int);
- classexample(int,int);
- …
- }
分析:上面的例子中类classexample有3个构造函数,在定义对象时,根据不同的参数调用相应的构造函数。
【示例4.15】 利用重载构造函数创建对象,在定义对象时,如果使用有参数的构造函数,那么必须指定参数值。定义对象时就可以调用相应的构造函数。
- #include <iostream.h>
- class classexample
- {
- private:
- int i; double d;
- public:
- classexample()
- {
- i=0;d=0.0;
- }
- classexample(int numi)
- {
- i=numi; d=0.0;
- }
- classexample(int numi,double numd)
- {
- i=numi;
- d=numd;
- }
- void print()
- {
- cout<<"i="<<i<<" "<<"d="<<d<<endl;
- }
- };
- void main()
- {
- classexample A;
- classexample B(3);
- classexample C(3,2.2);
- A.print();
- B.print();
- C.print();
-
- }
分析:上面的代码中首先定义一个类,并且对构造函数进行重载,在定义对象时,则会根据具体的参数选择合适的构造函数建立对象。上面程序的输出结果如下:
- i=0 d=0
- i=3 d=0
- i=3 d=2.2
前面介绍了重载构造函数的基本用法。在类中还存在一种构造函数,称为拷贝构造函数。拷贝构造函数是依据已经存在的对象建立新的对象,该构造函数的性质有以下几点:
函数名称和类名一样。
每个类都有一个拷贝构造函数,如果程序中没有显示定义,编译系统会自动生成一个拷贝构造函数。
拷贝构造函数有一个参数,是类的对象的引用。
【示例4.16】 利用拷贝构造函数实现point类的新对象,且把横纵坐标互换加倍。
- #include"iostream.h"
- #include"math.h"
- class point
- {
- private:
- int x;int y;
- public:
- float distance()
- {
- return sqrt(x*x+y*y);
- }
- point(int a,int b)
- {
- x=a;y=b;
- }
- point(const point &p)
- {
- x=2*p.y;y=2*p.x;
- }
-
- };
- void main()
- {
- point A(4,5);
- point B(A);
- cout<<A.distance()<<" "<<B.distance()<<endl;;
- }
分析:上面的拷贝构造函数是代入法,除此之外还可以采用赋值法。即利用赋值语句实现。如果用户未定义拷贝构造函数,那么系统会利用默认的拷贝构造函数实现赋值。
【责任编辑:
云霞 TEL:(010)68476606】