利用构造函数对类对象进行初始化及构造函数的重载

目录

对象的初始化

用构造函数实现数据成员的初始化

带参数的构造函数

用参数初始化表对数据成员初始化

构造函数的重载

使用默认参数的构造函数


对象的初始化

类不是实体,而是一种抽象数据类型,并不占存储空间,所以不能在类的声明中对类的数据成员进行初始化。

用构造函数实现数据成员的初始化

构造函数是一种特殊的成员函数,与其他成员函数不同,不需要用户调用它,在建立对象时自动执行。

构造函数的名字与类名相同,没有类型,没有返回值。

构造函数一般声明为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;
}

这种方法最为常用,相当于很多个重载的构造函数。

在没有参数时,用默认参数进行初始化,不会出错。

应该在声明构造函数时指定默认值,使用户知道在建立对象时怎样使用默认参数。

一般不同时使用构造函数的重载和有默认参数的构造函数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值