用C++设计一个学生类包含姓名、年龄、学号和成绩等私有成员变量。为这个类添加公有成员函数用于设置和获取学生的信息。要求设置学生的信息时输入的年龄和成绩必须大于0学号必须为正整数获取学生的信息时只能获取学生的姓名、年龄、学号和成绩。
#include<iostream>
using namespace std;
class Student{
private:
string name; //姓名
int age; //年龄
int id; //学号
float score; //成绩
public:
void setName(string name); //设置姓名
void setAge(int age); //设置年龄
void setId(int id); //设置学号
void setScore(float score); //设置成绩
string getName(); //获取姓名
int getAge(); //获取年龄
int getId(); //获取学号
float getScore(); //获取成绩
};
void Student::setName(string name){
this->name = name;
}
void Student::setAge(int age){
if(age <= 0){
cout << "年龄不能小于等于0!" << endl;
return;
}
this->age = age;
}
void Student::setId(int id){
if(id <= 0){
cout << "学号必须为正整数!" << endl;
return;
}
this->id = id;
}
void Student::setScore(float score){
if(score <= 0){
cout << "成绩不能小于等于0!" << endl;
return;
}
this->score = score;
}
string Student::getName(){
return this->name;
}
int Student::getAge(){
return this->age;
}
int Student::getId(){
return this->id;
}
float Student::getScore(){
return this->score;
}
int main(){
Student stu;
stu.setName("张三");
stu.setAge(20);
stu.setId(20210001);
stu.setScore(90.5);
cout << "姓名:" << stu.getName() << endl;
cout << "年龄:" << stu.getAge() << endl;
cout << "学号:" << stu.getId() << endl;
cout << "成绩:" << stu.getScore() << endl;
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/eDKl 著作权归作者所有。请勿转载和采集!