默认构造函数

默认构造函数:
没有参数的构造函数,称为默认构造函数。

1.合成的默认构造函数
但没有手动定义默认构造函数时,编译器自动为这个类定义一个构造函数。
1)如果数据成员使用了“类内初始值”,就使用这个值来初始化数据成员。【C++11】
2)否则,就使用默认初始化(实际上,不做任何初始化)

#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

//定义“人类”
class Human {
public: 
	void eat(); //类里面的方法,又称为成员函数
	void sleep();
	void work();
	void play();

	string getName();
	int getAge();
	int getSalary();

private:
	//类内初始值,C++11以上的版本才支持
	//在创建C++对象的时候,一开始就设定一个初始值,仅适用于特殊场合
	string name = "Evan";
	int age = 30; 
	int salary = 25000;
};

void Human::eat() {
	cout << "吃鸡屁股, 喝可乐!" << endl;
}

void Human::sleep() {
	cout << "夜深了!上床睡觉!" << endl;
}

void Human::work() {
	cout << "我在工作..." << endl;
}

void Human::play() {
	cout << "玩奇幻角色扮演!" << endl;
}

string Human::getName() {
	return name;
}

int Human::getAge() {
	return age;
}

int Human::getSalary() {
	return salary;
}

int main(void) {
	//以下的说明是在没有设置类内初始值的情况下
	//使用类Human创建一个对象,(创建一个对象必须调用构造函数)
	//此时,调用的构造函数就是默认构造函数
	//为了保持语法形式,没定义的时候,也弄一个构造函数去调用,没有实际意义
	//合成的默认构造函数让我们不用定义构造函数,编译器自己生成, 仅适用于\
	没有参数的构造函数
	Human b1;

	cout << b1.getName() << endl;
	cout << b1.getAge() << endl;
	cout << b1.getSalary() << endl;

	

	system("pause");
	return 0;
}

注意:
1)只要手动定义了任何一个构造函数,编译器就不会生成“合成的默认构造函数”
2)一般情况下,都应该定义自己的构造函数,不要使用“合成的默认构造函数”

3)适宜使用“合成的默认构造函数”的情况:
【仅当数据成员全部使用了“类内初始值”,才宜使用“合成的默认构造函数”】

2.手动定义的默认构造函数
常称为“默认构造函数”

#include <iostream>
#include <string>

using namespace std;

//定义“人类”
class Human {
public: //公有的, 公共的
	//void eat() {
	//直接在类里面写函数的内容,这样的函数叫做内联函数
	//...
//}	
	Human(); //构造函数,可以写在类里面(有内联函数的效果),也可以写在外面
	void eat(); //类里面的方法,又称为成员函数
	void sleep();
	void work();
	void play();

	string getName();
	int getAge();
	int getSalary();

private:
	//类内初始值,C++11以上的版本才支持
	//在创建C++对象的时候,一开始就设定一个初始值,仅适用于特殊场合
	string name = "牛少侠";
	int age = 23;
	int salary = 10000;
};

void Human::eat() {
	cout << "吃鸡屁股, 喝可乐!" << endl;
}

void Human::sleep() {
	cout << "夜深了!上床睡觉!" << endl;
}

void Human::work() {
	cout << "我在工作..." << endl;
}

void Human::play() {
	cout << "玩奇幻角色扮演!" << endl;
}

string Human::getName() {
	return name;
}

int Human::getAge() {
	return age;
}

int Human::getSalary() {
	return salary;
}

//没有设置类内初始值时,进行手动构造函数
Human::Human() {
	name = "无名";
	age = 18;
	salary = 30000;
}

int main(void) {
	//使用类Human创建一个对象,(创建一个对象必须调用构造函数)
	//此时,调用的构造函数就是默认构造函数
	Human b1;

	cout << b1.getName() << endl;
	cout << b1.getAge() << endl;
	cout << b1.getSalary() << endl;
	
	return 0;
}

输出为:
在这里插入图片描述

说明:
如果某数据成员使用类内初始值,同时又在构造函数中进行了初始化,
那么以构造函数中的初始化为准。
相当于构造函数中的初始化,会覆盖对应的类内初始值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值