c++ - 动态内存分配给指向对象的指针数组

标签 c++ pointers object dynamic

我有一个名为学生类(class)

class Student
{   string name;
    unsigned long int ID ;
    string email;
    unsigned short int year;
    public : 
         Student() // Constructor
         string getName(void);
         unsigned long int getID(void);
         string getEmail(void);
         unsigned short int getYear(void);   
{

和另一个名为 eClass

的类
class eClass {
 private:
 string eclass_name;
  Student* students[100];
  unsigned int student_count;

   public:
    eClass(string name)
    {
        student_count  =0 ; 
        eclass_name = name  ; 
    }

        bool exists(Student obj)
    {
        unsigned long int code = obj.getID();
        bool flag = TRUE ;
        for (unsigned int i = 0 ; i<=student_count ; i++ )
        {
            unsigned long int st = (*students[i]).getID();
            if (code==st)
            {
                flag = FALSE;
            }
        }
        return flag;
    }


        void add(Student& obj)
    { 
        bool res = exists(obj);
        if (res)
        {
            students[student_count] = new Student(); //probably the problem is here
            *students[student_count] = obj ;  
            student_count++ ; 
        }
    }

    string getEclassName(void) { return eclass_name; }
    unsigned int getStudentCount(void) { return student_count; }
    Student getStudent(int i) { return *students[i-1]; }


     };    

声明 Student* students[100]; 必须看起来完全像这样。例如我不能这样写: Student* students[100]={} ;

main() 看起来像这样

    int main()
   {
     Student    JohnDoe("John Doe", 12345,  2,  "johndoe@gmail.gr");
     eClass Cpp("C++"); 
     Cpp.add(JohnDoe);


     }

基本上我有一个指向 Student 对象的指针数组,每次我想添加一个新的 Student 对象时我都想动态分配内存。

当我编译时没有出现错误,但是当我尝试运行该程序时,我唯一得到的是“Program_name.exe”停止运行...

我很确定问题与内存分配有关,但我无法找到并解决它。

有什么建议吗?

最佳答案

exists 中的主要错误是循环走得太远,使用了未初始化的指针。但是 exists 按值获取输入也是非常糟糕的风格。修复这两个问题:

bool exists(Student const& obj)
{
    unsigned long int code = obj.getID();
    bool flag = TRUE ;
    for (unsigned int i = 0 ; i<student_count ; i++ )
    {
        unsigned long int st = (*students[i]).getID();
        if (code==st)
        {
            flag = FALSE;
        }
    }
    return flag;
}

您应该在 student 中声明 getID() 常量,以便能够正确编码 exists

unsigned long int getID() const;

关于c++ - 动态内存分配给指向对象的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34205217/

相关文章:

javascript - 对象传播运算符在 Microsoft Edge 中抛出错误

javascript - 有人可以解释一下向对象添加新属性的循环过程吗?

JavaScript Object.prototype 按值

c++ - 从 std 包装 C++ 功能有时是个坏主意?

c++ - vkCreateInstance 抛出段错误

c - C 中的指针数组?

c - 确保只将指针传递给可变参数函数

c++ - 了解多继承的vptr?

c++ - 使用初始化列表程序工作正常,但直接分配时却不行

c - 从 C 中的函数返回数组