编写一个Person类,包括:1) 普通数据成员:姓名,性别,年龄。2) 三个构造函数:无参数构造函数,有参数构造函数(参数:姓名,年龄,性别),拷贝构造函数。3) 析构函数,输出人员信息函数print()。编写main()函数,分别调用三种构造函数,创建三个对象P1、P2、P3。
时间: 2023-06-10 14:02:37 浏览: 219
好的,我已经记下了。以下是答案:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Person {
private:
char name[20];
char gender[10];
int age;
public:
// 无参数构造函数
Person() {
strcpy(name, "");
strcpy(gender, "");
age = 0;
}
// 有参数构造函数
Person(const char *n, int a, const char *g) {
strcpy(name, n);
strcpy(gender, g);
age = a;
}
// 拷贝构造函数
Person(const Person &p) {
strcpy(name, p.name);
strcpy(gender, p.gender);
age = p.age;
}
// 析构函数
~Person() {
cout << "Destroying object of Person class" << endl;
}
// 输出人员信息
void print() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person P1; // 调用无参数构造函数
P1.print();
cout << endl;
Person P2("Tom", 22, "Male"); // 调用有参数构造函数
P2.print();
cout << endl;
Person P3 = P2; // 调用拷贝构造函数
P3.print();
cout << endl;
return 0;
}
```
希望能够对你有所帮助!
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)