出一个类与对象的题c++并给出答案
时间: 2024-03-05 21:54:04 浏览: 29
好的,这里是一道关于类与对象的C++题目:
定义一个名为"Person"的类,该类包含私有成员变量"name"和"age",并具有公有成员函数"setName"和"setAge"用于设置名称和年龄,以及公有成员函数"introduce"用于输出人物的信息(例如:"我叫XXX,今年XX岁")。
以下是代码示例:
```
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
void introduce() {
cout << "我叫" << name << ",今年" << age << "岁" << endl;
}
};
int main() {
Person p;
p.setName("张三");
p.setAge(20);
p.introduce();
return 0;
}
```
答案解析:
这道题要求我们定义一个名为"Person"的类,包含私有成员变量"name"和"age",以及公有成员函数"setName"、"setAge"和"introduce"。其中,"setName"和"setAge"用于设置名称和年龄,而"introduce"用于输出人物的信息。
在代码中,我们使用了string类型的name和int类型的age,分别代表人物的名称和年龄。setName和setAge函数分别用于设置name和age的值,而introduce函数则使用cout输出人物的信息。在main函数中,我们首先创建了一个名为p的Person对象,然后使用setName和setAge函数分别设置了p的名称和年龄,最后使用introduce函数输出了p的信息。
以上就是这道题的答案解析。