定义一个描述学生基本情况的类,数据成员包括:年龄、姓名、性别;成员函数包括:输入和输出各个数据成员的值。
时间: 2023-12-10 11:40:11 浏览: 136
下面是一个基本的学生类的定义示例:
```c++
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int age;
string name;
char gender;
public:
void setAge(int a) { age = a; }
void setName(string n) { name = n; }
void setGender(char g) { gender = g; }
int getAge() const { return age; }
string getName() const { return name; }
char getGender() const { return gender; }
void input() {
cout << "请输入学生姓名:";
cin >> name;
cout << "请输入学生年龄:";
cin >> age;
cout << "请输入学生性别(M/F):";
cin >> gender;
}
void output() const {
cout << "学生姓名:" << name << endl;
cout << "学生年龄:" << age << endl;
cout << "学生性别:" << gender << endl;
}
};
```
在这个示例中,我们定义了一个名为`Student`的类,它有三个私有的数据成员`age`、`name`和`gender`,分别表示学生的年龄、姓名和性别。我们还定义了三个公有的成员函数`setAge()`、`setName()`和`setGender()`,用于设置这些数据成员的值;以及三个公有的成员函数`getAge()`、`getName()`和`getGender()`,用于获取这些数据成员的值。接下来,我们定义了两个公有的成员函数`input()`和`output()`,前者用于输入学生的基本信息,后者用于输出学生的基本信息。
使用示例:
```c++
int main() {
Student stu;
stu.input();
stu.output();
return 0;
}
```
输出结果:
```
请输入学生姓名:Tom
请输入学生年龄:18
请输入学生性别(M/F):M
学生姓名:Tom
学生年龄:18
学生性别:M
```
阅读全文