#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
using namespace std;
int HumanCount ;
// 定义一个“人类”
#include <iostream>
class Human {
public:
Human();
Human(int age, int salary,string bldType);
Human(const Human&); //不定义拷贝构造函数,编译器会生成“合成的拷贝构造函数”
void eat();
void sleep();
void play();
void work();
int getAge();
int getSalary();
void setAddr(const char *newAddr);
const char* getAddr();
int getHC();
void description();
private:
char name ;
int age ;
int salary;
char *addr;
const
static int HC =0 ;
const string bloodType ;
};
//初始化列表。
Human::Human():bloodType("A") {
age = 18;
salary = 30000;
HumanCount ++ ;
//bloodTypeY由于是只读常量,因此不能修改,如果要修改,只有如下的方法才行
cout<<&HumanCount<<endl;
}
//使用 blodType(bldType)进行灵活的初始化,这样就可以对bldtype进行修改
Human::Human(int age, int salary,string bldType):bloodType(bldType) {
cout << "调用自定义的构造函数" << endl;
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->salary = salary;
addr = new char[64];
strcpy_s(addr, 64, "China");
HumanCount ++ ;
cout <<&HumanCount<<endl;
}
Human::Human(const Human &man) {
cout << "调用自定义的拷贝构造函数" << "参数:" << &man
<< " 本对象:" << this << endl;
age = man.age; //this是一个特殊的指针,指向这个对象本身
salary = man.salary;
name = man.name;
// 深度拷贝
addr = new char[64];
strcpy_s(addr, 64, man.addr);
HumanCount++;
cout<<&HumanCount<<endl;
}
void Human::eat() {
cout << "吃炸鸡,喝啤酒!" << endl;
}
int Human::getHC() {
cout<<HC<<endl;
return HC;
}
void Human::sleep() {
cout << "我正在睡觉!" << endl;
}
void Human::play() {
cout << "我在唱歌! " << endl;
}
void Human::work() {
cout << "我在工作..." << endl;
}
int Human::getAge() {
return age;
}
int Human::getSalary() {
return salary;
}
void Human::setAddr(const char *newAddr) {
if (!newAddr) {
return;
}
strcpy_s(addr, 64, newAddr);
}
const char* Human::getAddr() {
return addr;
}
void Human::description(){
cout<<"age"<<age<<endl;
cout <<"salary"<<salary<<endl;
cout<<"bloddtype"<<bloodType<<endl;
}
void test(Human man) {
cout << man.getSalary() << endl;
}
void test2(Human &man) { //不会调用拷贝构造函数,此时没有没有构造新的对象
cout << man.getSalary() << endl;
}
Human test3(Human &man) {
return man;
}
Human& test4(Human &man) {
return man;
}
void test(){
Human tmp1;
Human tmp2;
cout<<HumanCount<<endl;
}
int main(void) {
Human h1(25,3000,"B");
Human h2;
test();
h1.getHC();
cout<<HumanCount<<endl;
h1.description();
h2.description();
system("pause");
return 0;
}
05-23
465