/* Human.h */
#include <string>
class Human {
private:
std::string name;
unsigned int age;
public:
/*构造函数与类同名,在创建对象时被调用,当没有定义构造函数时,系统将调用一个默认的构造函数
* 析构函数,在对象被销毁时调用
*/
Human(std::string str = "Jony", unsigned int num = 20);//带默认参数的重载构造函数, 只在声明的地方写值,定义的地方可以不写
Human::~Human();
void setName(std::string str);
void setAge(unsigned int num);
void getName();
void getAge();
};
/*Human.cpp*/
#include <iostream>
#include "Human.h"
Human::Human(std::string str, unsigned int num)//只在声明的地方写值,定义的地方可以不写
{
name = str; //构造函数可初始化类的数据,防止生成垃圾值
age = num;
std::cout << "2 call Human(----) name = " << name << std::endl;
}
Human::~Human()
{
std::cout << "3 call ~Human() the name is " << name << std::endl;
}
void Human::setName(std::string str)
{
name = str;
}
void Human::setAge(unsigned int num)
{
age = num;
}
void Human::getName()
{
std::cout << "3 the person's name is " << name << std::endl;
}
void Human::getAge()
{
std::cout << "the person's age is " << age << std::endl;
}
#include <iostream>
#include <string>
#include "Human.h"
int main()
{
Human man_one; //实例化对象,调用构造函数,当对象被销毁时(函数退出时),调用析构函数
Human man_two("Haha");
Human* woman_two = new Human("Luca", 20);//实例化对象,调用构造函数,当对象被销毁时(delete时),调用析构函数
delete woman_two;
return 0;
}
输出:
2 call Human(----) name = Jony
2 call Human(----) name = Haha
2 call Human(----) name = Luca
3 call ~Human() the name is Luca
3 call ~Human() the name is Haha
3 call ~Human() the name is Jony