cin >> name >> id >> gender >> city >> score;
s.set(name, id, gender, city, score);
s.showinfo();
cout << "成绩:" << s.getscore() << endl;
return 0;
下面是一个示例的C++代码,实现了一个学生类,包含基本信息(姓名、年龄、性别、学号)以及相应的set函数、get函数和show函数。
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 构造函数
Student(string name = "", int age = 0, char gender = 'M', string id = "") :
name_(name), age_(age), gender_(gender), id_(id) {}
// set函数
void setName(string name) { name_ = name; }
void setAge(int age) { age_ = age; }
void setGender(char gender) { gender_ = gender; }
void setId(string id) { id_ = id; }
// get函数
string getName() const { return name_; }
int getAge() const { return age_; }
char getGender() const { return gender_; }
string getId() const { return id_; }
// show函数
void show() const {
cout << "Name: " << name_ << endl;
cout << "Age: " << age_ << endl;
cout << "Gender: " << gender_ << endl;
cout << "ID: " << id_ << endl;
}
private:
string name_; // 姓名
int age_; // 年龄
char gender_; // 性别
string id_; // 学号
};
在上面的代码中,首先定义了一个学生类Student,包含四个私有属性name_、age_、gender_、id_,分别表示学生的姓名、年龄、性别、学号。这些属性都可以通过相应的set函数进行设置,也可以通过get函数获取单个属性的值。此外,还实现了一个show函数,用于将学生类的所有属性信息打印到屏幕上。
在使用时,可以先创建一个学生类对象,然后通过set函数设置该对象的各个属性值,最后可以通过get函数获取单个属性的值,或者通过show函数将所有属性信息打印到屏幕上。例如:
int main() {
Student stu;
stu.setName("Tom");
stu.setAge(18);
stu.setGender('M');
stu.setId("20190001");
cout << "Name: " << stu.getName() << endl;
cout << "Age: " << stu.getAge() << endl;
cout << "Gender: " << stu.getGender() << endl;
cout << "ID: " << stu.getId() << endl;
stu.show();
return 0;
}
输出结果为:
Name: Tom
Age: 18
Gender: M
ID: 20190001
Name: Tom
Age: 18
Gender: M
ID: 20190001
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
string id;
char gender;
string city;
int score;
public:
void set(string name, string id, char gender, string city, int score) {
this->name = name;
this->id = id;
this->gender = gender;
this->city = city;
this->score = score;
}
string getname() { return name; }
string getid() { return id; }
char getgender() { return gender; }
string getcity() { return city; }
int getscore() { return score; }
void showinfo() {
cout << "姓名:" << name << endl;
cout << "学号:" << id << endl;
cout << "性别:" << gender << endl;
cout << "城市:" << city << endl;
cout << "成绩:" << score << endl;
}
};
int main() {
Student s;
string name;
string id;
char gender;
string city;
int score;
cin >> name >> id >> gender >> city >> score;
s.set(name, id, gender, city, score);
s.showinfo();
cout << "成绩:" << s.getscore() << endl;
return 0;
}