构建一个人类的类,里面包含各种方法和属性,来展示构造函数(默认构造函数、自定义构造函数、拷贝构造函数)的使用:
#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;
}
运行结果如下: