首页 文章

从另一个类创建对象并将它们添加到数组[C]

提问于
浏览
0

我是C的新手并且遇到了问题 . 我希望类Admin能够创建Student类的新对象,并将对象添加到包含所有学生信息的数组中 . 我怎么能在Admin类中做到这一点?

#include <iostream>
#include <string>
#include <sstream>

using namespace std;



class Student
{

public:

    int SSN_LENGTH = 9, MIN_NAME_LEN = 1, MAX_NAME_LEN = 40;
    string DEFAULT_NAME = "no name", DEFAULT_SSN = "000000000";

private:
    string studentName, SSN;


public:
    // constructor declarations
    Student();
    Student( string studentName, string SSN);

    // Accessors
    string getSSN(){ return SSN; }
    string getStudentName(){ return studentName; }


    // Mutators
    bool setSSN(string SSN);
    bool setStudentName(string studentName);

};

class Admin
{

private:
    static const int Student_MAX_SIZE = 100000;


public:
    bool addStudent (string studentName, string SSN);

};

1 回答

  • 1

    我如何在Admin类中执行此操作?

    使用 std::vector ,如下面的代码所示:

    #include <vector>
    //...
    class Admin
    {
        private:
            static const std::size_t Student_MAX_SIZE = 100000;
            std::vector<Student> vStudent;
    
        public:
            bool addStudent (string studentName, string SSN)
            {
               if ( vStudent.size() < Student_MAX_SIZE )  
               {
                   vStudent.push_back(Student(studentName, SSN));  
                   return true;
               }
               return false;
            }
    };
    

相关问题