定义一个描述学生基本情况的类,数据成员包括:年龄、姓名、性别;成员函数包括:输入和输出各个数据成员的值。 分别给出如下的3个文件: ①含类定义的头文件student.h, //student.h class Student { public: void display( ); private: int num; char name[20]; char sex; }; ②包含成员函数定义的源文件student.cpp //student.cpp #include <iostream> using namespace std; #include "student.h" void Student::display( ) { cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl; } ③包含主函数的源文件main.cpp。 为了组成一个完整的源程序,应当有包括主函数的源文件: //main.cpp #include <iostream> using namespace std; #include "student.h" int main( ) {Student stud; stud.display(); return 0; } 请完善该程序,在类中增加一个对数据成员赋初值的成员函数set_value。修改补充代码并上机运行
时间: 2023-11-27 19:54:53 浏览: 60
/student.h
```c++
class Student {
public:
void display();
void set_value(int n, char *nam, char s);
private:
int num;
char name[20];
char sex;
};
```
/student.cpp
```c++
#include <iostream>
#include "student.h"
using namespace std;
void Student::display() {
cout << "num: " << num << endl;
cout << "name: " << name << endl;
cout << "sex: " << sex << endl;
}
void Student::set_value(int n, char *nam, char s) {
num = n;
strcpy(name, nam);
sex = s;
}
```
/main.cpp
```c++
#include <iostream>
#include "student.h"
using namespace std;
int main() {
Student stud;
stud.set_value(1001, "Tom", 'M');
stud.display();
return 0;
}
```
相关问题
定义一个描述学生基本情况的类,数据成员包括:年龄、姓名、性别;成员函数包括:输入和输出各个数据成员的值。
下面是一个基本的学生类的定义示例:
```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
```