1、定义一个“person”类保存在“person.h”中
时间: 2023-11-17 20:05:42 浏览: 35
以下是一个简单的“person”类的定义,保存在“person.h”中:
```c++
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person {
public:
Person(); // 默认构造函数
Person(const std::string& name, int age); // 带参数的构造函数
~Person(); // 析构函数
// getter 和 setter
std::string getName() const;
int getAge() const;
void setName(const std::string& name);
void setAge(int age);
void introduce() const; // 自我介绍
private:
std::string m_name; // 姓名
int m_age; // 年龄
};
#endif // PERSON_H
```
其中,类的成员函数包括:
- 默认构造函数 `Person()`:用于创建一个空的`Person`对象。
- 带参数的构造函数 `Person(const std::string& name, int age)`:用于创建一个带有姓名和年龄的`Person`对象。
- 析构函数 `~Person()`:用于销毁`Person`对象。
- getter和setter函数:用于获取和设置`Person`对象的姓名和年龄。
- 自我介绍函数 `introduce() const`:用于打印`Person`对象的姓名和年龄。