20191225C++对象之构造函数,包括带参数的构造函数、拷贝函数、赋值构造函数

#include <Windows.h>
#include<iostream>
#include<string>
#define ADDR_LEN 128
using namespace std;

class Human {
	public:
		Human();//默认的构造函数
		Human(string name, int salary, int age);//自定义的构造函数
		Human(const Human & );//自定义拷贝构造函数
		Human& operator=( const Human &other);  //= 运算符 赋值构造函数,


		int getAge() const;
		string getName() const;
		int getSalary() const;
		void description() const;//信息描述
		
		void setAddr(const char* addr);
		char* getAddr() const;
	private:
		int age;
		string name;
		int salary;
		char* addr;//地址
};
Human::Human() {
	age = 20;
	name = "lee";
	salary = 60000;
}
Human::Human(string name, int age, int salary) {
	cout << "正在调用自定义构造函数Human(string name, int age, int salary)" << endl;
	this->name = name;
	this->age = age;
	this->salary = salary;
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, "中国");
}
Human::Human(const Human &other) {
	cout << "正在调用自定义的拷贝构造函数Human(const Human& other)" << endl;
	name = other.name;
	age = other.age;
	salary = other.salary;
	addr = new char[ADDR_LEN];
	strcpy_s(this->addr, ADDR_LEN, other.addr);
}
Human& Human::operator=(const Human& other) {//= 赋值构造函数
	//检测是不是自己给自己赋值
	if (this == &other) {
		return *this;
	}
	//如果有必要,先释放自己的内存
	//delete[] addr;
	//addr=new char[ADDR_LEN];
	name = other.name;
	age = other.age;
	salary = other.salary;
	strcpy_s(addr, ADDR_LEN, other.addr);

	//返回对象本身的引用,以便做连续赋值运算 a=b=c 
	return *this;
}


int Human::getAge() const{
	return age;
}
string Human::getName() const{
	return name;
}
int Human::getSalary() const{
	return salary;
}
void Human::setAddr(const char* addr) {
	if (!addr) {
		return;
	}
	strcpy_s(this->addr, ADDR_LEN, addr);
}
char* Human::getAddr() const {
	return addr;
}
void Human::description() const{
	cout << "名字:" << getName() << " 年龄:" << getAge() << " 薪水:" << getSalary() <<" 居住地:"<<getAddr()<< endl;
}
void showMSG(const Human &h) { //增加const 是希望调用此函数的时候不更改原对象的值
	cout << "自定义的消息函数:showMSG()" << endl;
	cout << h.getName() << "的消息如下:" << endl;
	h.description();

}

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

int main() {
	//Human lee("李军",38,50000);
	//showMSG(lee);

	Human h1("zhangsan", 20, 20000);
	Human h2("lisi", 22, 25000);
	getBetterMan(h1, h2);

	system("pause");
	return 0;
}
发布了51 篇原创文章 · 获赞 0 · 访问量 531

猜你喜欢

转载自blog.csdn.net/weixin_40071289/article/details/103703906