c++ - 打印对象数组

标签 c++ arrays class object

我想打印两个类的对象数组。我有类学生作为 Base 类,CS_studentIS_student 派生类,我有一个学生类型的数组,我想打印它在类大学的打印功能中。

我想要 3 个选项:

  1. 打印所有 CS_student 。
  2. 打印所有 IS_student 。
  3. 打印所有 CS_student 和 IS_student。

但它只打印一个对象。这是我的代码

class student (){
int ID;
string first_Name;
string last_Name;

public:
virtual void print ()=0; };

class CS_student ():public student {

public:
    void print(){
        cout<<" CS student "<<endl;}
};
class IS_student():public student {

public:
    void print(){
        cout<<"IS student"<<endl;}
};
class university {
    student **S;
    int size;
public :
    university (){
        S= new student *[size];
        size = 10;}
        ........
        ........

        void Print(){
            int y;
            cout<<"enter 1 to print CS student , enter 2 to print IS 
    student , enter 3 to print all CS and IS students";
            cin>>y;
            switch(y){
                case 1:{
                    for ( int i =0 ; i<size ; i++){
                      student * obj = S[i];
                      CS_student *obj2 = dynamic_cast<CS_student*>(obj);
                      if(obj2){
                     obj2->print();}
                    }
                       }
                       break;
                case 2:{
                    for ( int i =0 ; i<size ; i++){
                      student * obj = S[i];
                      IS_student *obj2 = dynamic_cast<IS_student*>(obj);
                      if(obj2){
                     obj2->print();}
                    }
                       }
                       break;
                case 3:{
                    for ( int i =0 ; i<size ; i++){
                       S[i]->print();}
                    break;
                default:{
                    cout<<"Error";
                        }
                       }
            }
        }
};

最佳答案

在设置 size=10 之前,您正在初始化 S= new student *[size];。您应该在使用前初始化 size 变量。

关于c++ - 打印对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20731632/

相关文章:

c++ - 以高效的方式创建、访问、存储和加载 boost::bimap

c++ - [] 运算符如何工作?

c - 数组的奇怪行为是循环内外不同的值

c++ - 为什么不首先将类(class)成员设置为公开?

c++ - 我应该使用哪些编译标志来避免运行时错误

c++ - 使用可编辑的 QComboBox 从列表中选择值或获取手动输入

c++ - 具有继承性的数据结构。初始化问题

javascript - 使用 Jquery 查找并计算字符串

javascript - 无法连接到 Node JS 上的 Mysql 数据库

ruby - 在类的实例上动态调用方法(用户动态指定实例名称)