#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;
}
C++ 学生类设计:封装姓名、年龄、学号、成绩信息

原文地址: http://www.cveoy.top/t/topic/nUYd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录