第十八节 C++ - 带默认参数值的构造函数

这篇博客探讨了C++中的构造函数如何使用默认参数值。通过实例展示了带默认参数值的构造函数如何被调用,以及析构函数的执行顺序。
摘要由CSDN通过智能技术生成
/* Human.h */
#include <string>

class Human {
private:  
	std::string name; 
	unsigned int age;

public:
	/*构造函数与类同名,在创建对象时被调用,当没有定义构造函数时,系统将调用一个默认的构造函数
	* 析构函数,在对象被销毁时调用
	*/
	Human(std::string str = "Jony", unsigned int num = 20);//带默认参数的重载构造函数, 只在声明的地方写值,定义的地方可以不写
	Human::~Human();
	void setName(std::string str); 
	void setAge(unsigned int num);
	void getName();
	void getAge();
};

/*Human.cpp*/
#include <iostream>
#include "Human.h"

Human::Human(std::string str, unsigned int num)//只在声明的地方写值,定义的地方可以不写
{
	name = str; //构造函数可初始化类的数据,防止生成垃圾值
	age = num;
	std::cout << "2 call Human(----) name = " << name << std::endl;
}

Human::~Human()
{
	std::cout << "3 call ~Human() the name is " << name << std::endl;
}

void Human::setName(std::string str)
{
	name = str;
}

void Human::setAge(unsigned int num)
{
	age = num;
}

void Human::getName()
{
	std::cout << "3 the person's name is " << name << std::endl;
}

void Human::getAge()
{
	std::cout << "the person's age is " << age << std::endl;
}

#include <iostream>
#include <string>
#include "Human.h"

int main()
{	
	Human man_one; //实例化对象,调用构造函数,当对象被销毁时(函数退出时),调用析构函数
	Human man_two("Haha");
	Human* woman_two = new Human("Luca", 20);//实例化对象,调用构造函数,当对象被销毁时(delete时),调用析构函数
	delete woman_two;
	return 0;
}

输出:

2 call Human(----) name = Jony
2 call Human(----) name = Haha
2 call Human(----) name = Luca
3 call ~Human() the name is Luca
3 call ~Human() the name is Haha
3 call ~Human() the name is Jony

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值