目录
对象的初始化
类不是实体,而是一种抽象数据类型,并不占存储空间,所以不能在类的声明中对类的数据成员进行初始化。
用构造函数实现数据成员的初始化
构造函数是一种特殊的成员函数,与其他成员函数不同,不需要用户调用它,在建立对象时自动执行。
构造函数的名字与类名相同,没有类型,没有返回值。
构造函数一般声明为public
#include<iostream>
using namespace std;
class Box{
public:
Box(); //构造函数
void show();
private:
int height;
int width;
int length;
};
int main(){
Box A;
A.show();
}
Box::Box(){
height=0;
width=0;
length=0;
}
void Box::show(){
cout<<height<<" "<<width<<" "<<length<<endl;
}
带参数的构造函数
#include<iostream>
using namespace std;
class Box{
public:
Box(int, int, int); //带参数的构造函数
void show();
private:
int height;
int width;
int length;
};
int main(){
Box a(1,2,3);
a.show();
Box b(10,15,20);
b.show();
}
Box::Box(int h,int w,int l){
height=h;
width=w;
length=l;
}
void Box::show(){
cout<<height<<" "<<width<<" "<<length<<endl;
}
用参数初始化表对数据成员初始化
参数初始化表可以减少构造函数的长度,更精炼简单,更方便在类体中定义。
注意:数组不能用参数初始化表。
Box(int h,int w,int l):height(h),width(w),length(l){} //参数初始化表
#include<iostream>
using namespace std;
class Box{
public:
Box(int h,int w,int l):height(h),width(w),length(l){} //参数初始化表
void show();
private:
int height;
int width;
int length;
};
int main(){
Box a(1,2,3);
a.show();
Box b(10,15,20);
b.show();
}
void Box::show(){
cout<<height<<" "<<width<<" "<<length<<endl;
}
构造函数的重载
构造函数重载后,程序根据参数选择调用哪个构造函数。
在建立对象时不必给出实参的构造函数成为默认构造函数。
#include<iostream>
using namespace std;
class Box{
public:
Box();
Box(int h,int w,int l):height(h),width(w),length(l){} //参数初始化表
void show();
private:
int height;
int width;
int length;
};
int main(){
Box a;
a.show();
Box b(10,15,20);
b.show();
}
Box::Box(){
height=10;
width=10;
length=10;
}
void Box::show(){
cout<<height<<" "<<width<<" "<<length<<endl;
}
使用默认参数的构造函数
构造函数的参数的值既可以通过实参传递,也可以指定默认值。
#include<iostream>
using namespace std;
class Box{
public:
Box(int h=10,int w=10,int l=10); //声明构造函数时指定默认参数
void show();
private:
int height;
int width;
int length;
};
int main(){
Box a;
a.show();
Box b(10,15,20);
b.show();
}
Box::Box(int h,int w,int l){
height=h;
width=w;
length=l;
}
void Box::show(){
cout<<height<<" "<<width<<" "<<length<<endl;
}
这种方法最为常用,相当于很多个重载的构造函数。
在没有参数时,用默认参数进行初始化,不会出错。
应该在声明构造函数时指定默认值,使用户知道在建立对象时怎样使用默认参数。
一般不同时使用构造函数的重载和有默认参数的构造函数。