栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C++基础构造函数入门

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++基础构造函数入门

定义 构造函数 是一个 特殊的成员函数,名字与类名相同 , 创建类类型对象时由编译器自动调用 ,以保证每个数据成员都有一个合适的初始值,并且在对象整个生命周期内只调用一次。
#include
using namespace std;
class Date
{
public:

	Date(int year = 1999, int month = 1, int day = 1)//构造函数
	{
		_year = year;
		_month = month;
		_day = day;
	}

private:

	int _year;

	int _month;

	int _day;
};

int main()
{
	Date d1;//Date d1()这样写必须要给参数不然报错
	Date d1;//多次会报错,重定义

	return 0;
}

构造函数有四种,全缺省构造函数,无参构造函数,半缺省构造函数,默认构造函数,上面的Date就是全缺省构造函数

半缺省构造函数使用时记得传参

#include
using namespace std;
class Date
{
public:

	Date(int year, int month = 1, int day = 1)//半缺省构造函数
	{
		_year = year;
		_month = month;
		_day = day;
	}

private:

	int _year;

	int _month;

	int _day;
};

int main()
{
	Date d1(1900);//不传参会报错,不要写成Date d1();
	
	return 0;
}

无参构造函数

#include
using namespace std;
class Date
{
public:

	Date()//无参构造函数
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}

//也可以什么都不给
	Date()//无参构造函数,打印出结果为随机值
	{}

private:

	int _year;

	int _month;

	int _day;
};

int main()
{
	Date d1;//
	d1.print();
	return 0;
}

全缺省构造函数

#include
using namespace std;
class Date
{
public:

	Date(int year = 1900, int month = 1, int day = 1)//半缺省构造函数
	{
		_year = year;
		_month = month;
		_day = day;
	}

    //不可再写
    Date()
	{
	}


private:

	int _year;

	int _month;

	int _day;
};

int main()
{
	Date d1;//注意有了全缺省构造函数,不能再写无参构造函数,系统不知道调用哪一个
	
	return 0;
}

默认构造函数

如果我们自己没有写任何构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。

#include
using namespace std;
class Date
{
public:

  void print()
{
    cout<<_year<<" "<<_month<<" "<<_day< 
 

我们运行上述程序发现,编译器生成的默认构造函数好像没有什么用

 原因

C++ 把类型分成 内置类型(基本类型) 和 自定义类型 。 内置类型就是语言提供的数据类型,如:int/char...; 自定义类型就是我们使用 class/struct/union 等自己定义的类型。 其中 默认生成的构造函数,内置类型成员( 任何指针都属于内置类型)不做处理,自定义类型成员回去调用他的默认构造函数。 那我们是否可以在私有中给变量赋值,不让它为随机值?
#include
using namespace std;
class Date
{
public:

  void print()
{
    cout<<_year<<" "<<_month<<" "<<_day< 
  

答案是可以的

 但是需要说明的是这里并不是对变量进行初始化,而是给的缺省值

简单总结一下:

默认构造函数 1 、我们不写,编译器自动生成(不处理内置类型),自定义类型调用自己的默认构造函数 2 、我们自己写全缺省构造函数,一般不使用半缺省构造函数,防止忘记赋值产生错误 3 、我们自己写无参构造函数,不能和全缺省构造函数共存,只有有一个

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029063.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号