在C ++运行时动态创建类对象

时间:2013-12-09 02:25:18

标签: c++ class pointers

我正在尝试在运行时创建对象。我有一个未指定数量的对象要创建,我完全迷失了。我被告知要使用指针来做这个,但我不知道哪个地方甚至使用指针。

这是我的代码。

#include <iostream>
#include <string>
using namespace std;

class Consumer
{
public:
    int idNum;
    string info;
    int maxHours;
    Consumer(int, string, int);
    void display();
    void newCons();
};

Consumer::Consumer()
{
    idNum = id;
    info = in ;
    maxHours = hrs;
}

void Consumer::newCons()
{
    int idn;
    string npa;
    int mhrs;
    cout << "Please input the consumer's ID number." << endl;
    cin >> idn;
    cout << "Please input the consumer's full name, phone number, and address." << endl;
    cout << "Do not press enter until you have entered all three." << endl;
    cin >> npa;
    cout << "Please input the max number of hours the consumer spends purchasing products each week." << endl;
    cin >> mhrs;

    Consumer anotherCons(idn, npa, mhrs);

    return;
}

void Consumer::display()
{
    return;
}

int main()
{
    int i, howMany;
    Consumer* anotherCons;
    anotherCons = new Consumer();

    anotherCons->newCons();

    return 0;
}

2 个答案:

答案 0 :(得分:0)

使用std::vector :( #include <vector>

vector<Consumer> list;
for(int i = 0; i < num_you_want_to_create; ++i){
    Consumer c; //declare an object of type consumer, if it doesn't work, try:
    //Consumer c(1, "test", 1);
    list.push_back(c); //creates a new consumer
}

答案 1 :(得分:0)

anotherCons = new Consumer();
//            ^^^^^^^^^^^^^^

在这里,您将调用Customer类的默认构造函数。你已经为你的类定义了一个,但它没有前向声明(在类体中原型)。您有一个构造函数定义为:

Customer(int, string, int);

但这是一个完全不同的构造函数。你需要有一个默认构造函数的原型以及一个专门的构造函数:

Customer();
Customer(int, string, int);

此外,在newCons方法中,您可以调用上面的参数化构造函数。这将再次导致错误,因为您没有在您给我们的代码中的任何位置定义构造函数。您的构造函数应该像这样定义:

Customer::Customer(int id, string in, int hrs)
    : idNum(id), info(in), maxHours(hrs)
{ }

我们在这里使用 member-initializer 列表。您也可以将它与default-constructor一起使用。


@awesomeyi说的是正确的,您可以使用std::vector在运行时动态添加对象。它比手动分配释放内存更好,因为它是由向量的构造函数/析构函数手动完成的。

此外,我认为您的newCons功能应更改为:

static Consumer newCons();

我在回复类型中添加了static Consumer并删除了void。我为什么这样做?好吧,我正在返回Consumer因为它符合函数的语义 - 你想创建一个新的Consumer对象,但是当你创建它时你用它做什么?好吧,你必须让对象回到调用者,以便他们可以使用它,所以我决定最好返回一个新对象。在最后一行你会做:

Consumer anotherCons(idn, npa, mhrs);
return anotherCons;

return Consumer(idn, npa, mhrs);

到目前为止这很棒。以下是main的正文:

int main()
{
    std::vector<Consumer> v;
    v.push_back(Consumer());

    v.at(0) = Consumer::newCons();
}

这只是main的一个例子。你真正的代码可以是任何东西。

就个人而言,我认为最好为Consumer对象定义一个提取器,因为它符合标准IOStreams库的感觉。例如:

std::istream& operator>>(std::istream& is, Consumer& c)
{
    c = Consumer::newCons(is);
    return is;
}

这也需要Consumer::newCons取一个参数:

static Consumer newCons(std::istream& is)

并使用is代替cin

现在:

int main()
{
    std::vector<Consumer> v;

    Consumer c;
    std::cin >> c;

    v.push_back(c);
}