构造函数的初始化过程

//1.h	存放类的定义、类成员函数的原型等
#pragma once
#include<iostream>
#include<string>
class man	//创建类
{
private:
	std::string name;	//私有成员两个
	int year;
public:
	man();		//默认构造函数
	man(const std::string a, int b = 0);	//因为存在重载析构函数,因此不能提供2个默认参数
	inline void update()	//成员更新,使用内联函数
	{
		name = "帅", year = 99;
	}
	void show();			//显示
	~man();				//析构函数,输出文字,表示析构函数确实运行了
};


//1.cpp main()函数,赋值,及调用类方法
#include<iostream>
#include<string>
#include"1.h"		//调用包含类定义的头文件1.h

int main()
{
	using namespace std;
	man b;		//使用默认构造函数
	b.show();	//调用类方法,输出对象的值

	{					//用括号括起来的块,类对象只在块内存在
		cout << "这里开始在块内" << endl;
		man a("wd",27);	//使用自定义析构函数,并不使用默认参数
		a.show();
		man b("mmmm");	//使用自定义析构函数,并使用默认参数。另外,这里的b隐藏了块外的b
		b.show();
		b.update();		//更新对象的数据
		b.show();
	}
	cout << "这里在块外了" << endl;


	system("pause");
	return 0;
}

//2.cpp	存放类的函数定义
#include<iostream>
#include"1.h"

//因为是类的函数定义,因此要加上作用域解析运算符::

man::man()				//默认构造函数,构造函数和析构函数的返回值都不加void
{
	name = "\"NO NAME\"";	//提供默认值
	year = 0;
}
man::man(const std::string a, int b)	//因为存在重载析构函数,因此不能提供2个默认参数
{
	name = a;
	if (b < 0)
	{
		std::cout << "人不可能小于0岁,因此,设置为0岁" << std::endl;
		b = 0;
	}
	else year = b;
}
void man::show()		//显示
{
	using namespace std;
	cout << name << " is " << year << " years old." << endl;
}
man::~man()		//析构函数,输出文字,表示析构函数确实运行了
{
	std::cout << name << " end." << std::endl;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值