直接上代码:
#include<stdio.h>
#include<iostream.h>
class A{
private :
int a;
int b;
int c;
public :
A(int a=1,int b=1 ,int c=1){
this->a=a;
this->b=b;
this->c=c;
}
void print(){
cout<<"a = "<<a <<endl;
cout<<"b = "<<b <<endl;
cout<<"c = "<<c <<endl;
}
};
void main(){
A a(1,2,4);
a.print();
A b;
b.print();
}
在上述代码中,我们定义了一个含三个参数的构造函数
A(int a=1,int b=1 ,int c=1){
this->a=a;
this->b=b;
this->c=c;
}
而在mian()函数中,我们声明了两个A对象,
A a(1,2,4);
a.print();
A b;
b.print();
结果如下:
a = 1
b = 2
c = 4
a = 1
b = 1
c = 1
也可以将上述构造函数分开定义,结果相同,代码如下:
#include<stdio.h>
#include<iostream.h>
class A{
private :
int a;
int b;
int c;
public :
A(int a=1,int b=1 ,int c=1);//在声明构造函数时指定默认参数
void print(){
cout<<"a = "<<a <<endl;
cout<<"b = "<<b <<endl;
cout<<"c = "<<c <<endl;
}
};
A::A(int a,int b,int c)//在定义函数时可以不指定默认参数
{
this->a=a;
this->b=b;
this->c=c;
}
void main(){
A a(1,2,4);
a.print();
A b;
b.print();
}
可见当没有指定参数是,函数默认调用构造函数中给定的参数值int a=1,int b=1 ,int c=1。
读者可以考虑一下以下问题:
1、如果将mian()函数中定义语句改为:
A b(2,2);
b.print();
那么答案会如何?到底是a=1,还是c=1!
2、如果再重载一个无参的构造函数
A()
{
cout<<"无参数的构造函数"<<endl;
}
继续运行上述代码又会出现什么样的情况?
关于构造函数默认值的几点说明:
1、应该在声明构造函数时指定默认值,而不能只在定义构造函数时指定默认值。
2、在一个类中定义了全部是默认参数的构造函数后,不能再定义重载构造函数。
3、如果构造函数的全部参数都指定了默认值,则在定义对象时可以给一个或几个实参,也可以不给出实参。