0

我有 3 个文件。main.cpp、object.h 和 object.cpp。

主要是我试图创建一个包含 100 个对象指针的数组。然后,在创建数组后,我进入一个循环并遍历每个“i”元素并将该元素的值分配为指向新临时对象的指针,该临时对象将在字符串中传递。这样做的基本前提是,我可以使用它来存储多个对象,这些对象内部包含信息,之后我可以通过在这些点上调用函数来打印这些信息。我需要使用一组指针来执行此操作。

本质上,我想将数据存储在一个对象指针数组中,该数组将使用一个新的运算符来存储它每次迭代。但是,我不确定如何创建数组,因为它需要传入要调用的变量。

我试过 Object *ptr = new Object[arraySize]; 我确信这会起作用,但它需要参数,因为对象被定义为在其中获取变量。

主文件

#include <iostream>
#include "object.h"

int main()
{
    Object *ptr = new Object[5];
    for(i = 0; i < 5, i++) {
        ptr[i] = "Test";
        ptr -> print();
    }

}

对象.cpp

#include "object.h"
#include <iostream>

using namespace std;

Object::Object(string words)
{
    private_words = words;
}

void Object::print()
{
    cout << private_words << endl;
}

对象.h

#ifndef OBJECT_H
#define OBJECT_H

#include <string>

using namespace std;

class Object
{

    public:
        Object(string words);
        void print();
    private:
        string private_words;
};

#endif

关于我试图传递参数并同时将其设为数组这一事实,我遇到了多个难以理解的错误。Object *ptr = new Object()[5] 不起作用。

4

1 回答 1

1

您的Object类缺少默认构造函数,这就是为什么new Object[...]不起作用。您将不得不使用更像这样的东西:

#include <iostream>
#include "object.h"

int main()
{
    Object **ptr = new Object*[5];
    for(i = 0; i < 5, i++) {
        ptr[i] = new Object("Test");
    }

    // use ptr as needed ...

    for(i = 0; i < 5, i++) {
        ptr[i]->print();
    }

    // cleanup ...

    for(i = 0; i < 5, i++) {
        delete ptr[i];
    }
    delete[] ptr;
}

最好使用标准容器,让编译器为您管理内存。

在 C++11 之前:

#include <iostream>
#include <memory>
#include "object.h"

int main()
{
    // NOTE: std::auto_ptr is NOT a container-safe type...
    std::auto_ptr<Object>* ptr = new std::auto_ptr<Object>[5];
    for(i = 0; i < 5, i++) {
        ptr[i].reset(new Object("Test"));
    }

    // use ptr as needed ...

    for(i = 0; i < 5, i++) {
        ptr[i]->print();
    }

    // cleanup ...
    // only the array is needed manually, the individual elements
    // will clean themselves up when they are destructed ...

    delete[] ptr;
}

在 C++11 及更高版本中,请改用:

#include <iostream>
#include <vector>
#include <memory>
#include "object.h"

int main()
{
    // NOTE: std::unique_ptr IS a container-safe type...
    std::vector<std::unique_ptr<Object>> ptr(5);
    for(i = 0; i < 5, i++) {
        ptr[i].reset(new Object("Test"));

        // or:
        // ptr[i] = std::unique_ptr<Object>(new Object("Test"));

        // or, in C++14 and later:
        // ptr[i] = std::make_unique<Object>("Test");
    }

    // use ptr as needed ...

    for(i = 0; i < 5, i++) {
        ptr[i]->print();
    }

    // all cleanup is automatic when ptr goes out of scope ...
}
于 2019-02-19T02:57:02.460 回答