【问题标题】:How to allocate memory fo array of objects如何为对象数组分配内存
【发布时间】:2021-07-24 14:16:44
【问题描述】:

我正在尝试用 C++ 创建一个对象数组。由于 C++ 支持 int、float 等原生对象,因此创建它们的数组不是问题。

但是当我创建一个类并创建该类的对象数组时,它不起作用。

这是我的代码:

#include <iostream>
#include <string.h>

using namespace std;
class Employee
{
    string name;
    int age;
    int salary;

public:
    Employee(int agex, string namex, int salaryx)
    {
        name = namex;
        age = agex;
        salary = salaryx;
    }

    int getSalary()
    {
        return salary;
    }

    int getAge()
    {
        return age;
    }

    string getName()
    {
        return name;
    }
};
int main(void)
{
    Employee **mycompany = {};

    //Create a new Object
    mycompany[0] = new Employee(10, "Mayukh", 1000);
    string name = mycompany[0]->getName();
    cout << name << "\n";

    return 0;
}

没有编译错误,但是当我运行程序时,它崩溃了。我不知道这里到底发生了什么。

请帮忙。

这里有更多细节:

OS: 64bit Windows 8.1 on Intel x64 (i3) Architecture of Compiler: MinGW64 G++ Compiler

【问题讨论】:

  • 你的错误在这里:Employee **mycompany = {};mycompany[0] = new Employee(10, "Mayukh", 1000); 如果你要创建一个二维动态数组,你需要在使用它之前分配第一个维度。
  • @drescherjm,我该怎么做?我尝试做Employee *mycompany = {} 并删除了 new 关键字,因为它现在指向对象,但我的程序在运行时仍然崩溃。请帮忙。
  • 我注意到当我使用 Vectors 时,它可以正常工作。请告诉我哪里错了
  • int main(void) { vector&lt;Employee&gt; a; a.push_back(Employee(10, "Mayukh", 200)); string name = a[0].getName(); cout &lt;&lt; name &lt;&lt; "\n"; return 0; }

标签: c++ arrays object memory-management dynamic-memory-allocation


【解决方案1】:

与往常一样,这里的建议是使用一些 STL 容器,例如 std::vector

也就是说你可能需要一个默认的Employee 构造函数(除非你总是用你已经拥有的构造函数来初始化容器的所有元素,这不太可能是你想要的这样做,如果您要手动分配内存,但如果您使用std::vector,则更有可能)。

//...
Employee() = default; // or Employee(){}
Employee(int agex, string namex, int salaryx)
{
    name = namex;
    age = agex;
    salary = salaryx;
}
//...

如果你真的,绝对,必须手动分配内存,它大概是这样的:

// Employee array with 5 employees, with the first two initialized with your constructor
Employee *mycompany = new Employee[5] {{10, "Mayukh1", 1000}, {20, "Mayukh2", 2000}};

//adding an employee
mycompany[2] = {30, "Mayukh3", 3000};

// it still has space for 2 more

事后别忘了删除记忆:

delete [] mycompany;

Live demo

【讨论】:

    【解决方案2】:

    你会这样做:

    #include <iostream>
    #include <string.h>
    
    using namespace std;
    
    class Employee
    {
        string name;
        int age;
    
        int salary;
    
        public:
            Employee(int agex, string namex, int salaryx)
            {
                name = namex;
                age = agex;
                salary = salaryx;
            }
    
            int getSalary()
            {
                return salary;
            }
    
            int getAge()
            {
                return age;
            }
    
            string getName()
            {
                return name;
            }
    };
    
    int main(void)
    {
        //Create an Array length of 10 
        // in c++ its static you have to give the length of the array while declaring
        Employee mycompany [10];
    
        //Create a new Object
        mycompany[0] = new Employee(10, "Mayukh", 1000);
    
        string name = mycompany[0]->getName();
    
        cout << name << "\n";
    
        return 0;
    }
    

    【讨论】:

    • 我试过了,但我的问题是我实际上并不知道数组的实际大小,这意味着我正在使用动态大小的数组。 Vector 工作得很好,但我想知道为什么我的实现不起作用
    • 您需要默认构造函数,如另一个答案中所述。 Employee() = default; // or Employee(){}
    • 您可以创建一个函数来调整数组的大小,同时向其中添加新对象,我在这里使用 int 执行此操作,但您也可以使用 Employee 执行此操作c++ void addToArray(int *&amp;original, int &amp;SIZE, const int &amp;number) { int *temporiginal = new int[SIZE + 1]; //(final)new array for (int i = 0; i &lt; SIZE; i++) //copy old array to new array { temporiginal[i] = original[i]; } temporiginal[SIZE] = number delete[] original; //delete old array original = temporiginal; //point old array to new array }
    • 你也可以看看这里 :D cplusplus.com/forum/beginner/235218 可能比
    • 是的,你也需要一个构造函数见这里:w3schools.com/cpp/cpp_constructors.asp
    猜你喜欢
    • 2013-12-04
    • 1970-01-01
    • 2020-06-02
    • 2012-05-04
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多