C++面向对象的程序设计1——构造函数(默认构造函数、自定义构造函数、拷贝构造函数)

构建一个人类的类,里面包含各种方法和属性,来展示构造函数(默认构造函数、自定义构造函数、拷贝构造函数)的使用:

#include <iostream>
#include <string>
#include <Windows.h>
#define ADDR_LEN 64

using namespace std;

class Human{
public:
	Human();
	Human(string, int, int);
	Human(const Human &);
	void eat();
	void sleep();
	void paly();
	void work();
	string getName();   // 获取名字
	int getAge();       // 获取年龄
	int getSalary();    // 获取薪水
	char *getAddr();    // 获取地址
	void desprition();  // 描述
	void setAddr(char *);  // 设置地址

private:
	string name;
	int age;
	int salary;
	char *addr;
};

Human::Human(string name, int age, int salary)
{
	cout << "调用自定义的构造函数" << endl;
	this->name = name;
	this->age = age;
	this->salary = salary;
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, "China");
}

Human::Human(const Human &man)
{
	cout << "调用拷贝构造函数" << endl;
	name = man.name;
	age = man.age;
	salary = man.salary;
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, "china");   // 可以实现深拷贝,如果直接使用默认的拷贝构造函数将会使使用浅拷贝
}

void Human::eat()
{
	cout << "我正在吃" << endl;
}

void Human::sleep()
{
	cout << "我正在睡觉" << endl;
}

void Human::paly()
{
	cout << "我正在玩" << endl;
}

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

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

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

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

char *Human::getAddr()
{
	return addr;
}

void Human::setAddr(char *address)
{
	strcpy_s(addr, ADDR_LEN, address);
}

void Human::desprition()
{
	cout<< "name:" << name <<
		" age:" << age <<
		" salary:" << salary <<
		" addr:" << addr << endl;
}

void test(Human man)
{
	cout << "这是测试部分:调用函数时,实参是对象,形参不是引用类型" << endl;
}

void test2(const Human &man)
{
	cout << "这是测试部分:调用函数时,实参是对象,形参不是引用类型" << endl;
}

Human test3(Human &man1, Human &man2)
{
	if(man1.getSalary() > man2.getSalary()){
		return man1;
	}else {
		return man2;
	}
}

int main(void)
{
	Human h1("张三", 28, 30000);
	Human h2("李四", 30, 35000);
	Human h3(h1);   // 调用拷贝构造函数
	/* 深浅拷贝的演示 */
	h1.desprition();
	h3.desprition();
	h3.setAddr("American");
	h1.desprition();
	h3.desprition();

	/* 调用拷贝构造函数的情况 */
	Human h4 = h1;
	Human h5(h1);
	// 调用函数时,实参是对象,形参不是引用类型
	test(h1);
	test2(h1);
	// 函数的返回类型是类,而且不是引用类型
	test3(h1, h2);
	// 对象数组的初始化列表中,使用对象
	Human h_list[4] = {h1, h2, h3, h4};
	system("pause");
	return 0;
}

运行结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值