c++之路5:用类创建多个学生对象

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;
const int N = 5;      //定义整形常量,意义是创建的最多学生对象为5个,这里定义常量是方便修改下文
class Student
{
    private:
        char name[10];
        char sex[5];
        int age;
    public:
    void Stu_set()                                                                       
        { 
            cout<<"请输入该学生的姓名 性别 年龄:"<<endl;
            cin>>name>>sex>>age;
        }
    void Stu_show()       //显示创建学生对象信息
        {
            cout<<"姓名:"<<name<<"性别:"<<sex<<"年龄:"<<age<<endl; 
        }
};

int main()
{
    Student stu[N];
    int i=0;
    int n=0;
    int kong;
    do
    {                                             
        stu[i].Stu_set();
        i++;                              
        n=i;    //创建多少个对象n就为多少
        cout<<"继续输入请直接输入1,否则请输入0!"<<endl;   //控制是否继续创建学生对象信息
        cin>>kong;
  
    } while(kong!=0);       //用do~while();循环来创建多个学生信息对象,输入0停止创建

    for(i = 0; i < n; i++)
    {
        stu[i].Stu_show();
        return 0;
    }
}

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例代码: ```c++ #include <iostream> #include <string> using namespace std; class Student { private: string name; int age; public: Student(string n, int a) { name = n; age = a; } void display() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } }; class Class { private: Student* students; int size; public: Class(int s) { size = s; students = new Student[size]; } void addStudent(string name, int age, int index) { students[index] = Student(name, age); } void display() { for (int i = 0; i < size; i++) { students[i].display(); } } }; int main() { Class c(3); c.addStudent("Alice", 18, 0); c.addStudent("Bob", 19, 1); c.addStudent("Charlie", 20, 2); c.display(); return 0; } ``` 在上面的代码中,我们定义了两个类:`Student` 和 `Class`。`Student` 类表示一个学生,包含姓名和年龄两个属性和一个 `display` 方法用来打印学生信息。`Class` 类表示一个班级,包含一个 `Student` 对象数组和一个大小属性。它有一个 `addStudent` 方法可以添加学生到班级中,还有一个 `display` 方法可以打印整个班级的学生信息。 在 `main` 函数中,我们首先创建了一个大小为 3 的班级对象 `c`。然后,我们通过 `addStudent` 方法向班级中添加了三个学生。最后,我们通过 `display` 方法打印了整个班级的学生信息。 这个班级系统可以根据需要进行扩展,例如可以添加删除学生的功能,或者添加更多的学生信息,如成绩、家庭背景等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值