动态分配对象

时间:2014-01-30 20:40:05

标签: c++ oop

这是我的代码,我试图通过询问用户的大小来为对象分配内存。我不知道我哪里错了。编译器给我的错误是"void value not ignored as it ought to be"。请帮我。提前谢谢。

#include <iostream>
using namespace std;

class test
{
    char name[20];
    char address[30];
    char desig[20];
public:
    void getData();
    void display();
    ~test()
    {
        cout << "Destructor is invoked";
    }
};

void test::getData()
{
    cout << "Enter your name" << endl;
    cin >> name;

    cout << "Enter address" << endl;
    cin >> address;

    cout << "Enter designation" << endl;
    cin >> desig;
}

void test::display()
{
    cout << "name" << endl;
    cout << name << endl;

    cout << "address" << endl;
    cout << address;

    cout << "Enter designation" << endl;
    cout << desig;
}

int main()
{

    int s;
    cout << "Enter the size of an array" << endl;
    cin >> s;

    test* p1 = new test[s];

    for (int i = 0; i < s; i++)
    {
        *p1[i].getData();
    }

    for (int i = 0; i < s; i++)
    {
        *p1[i].display();
    }

    delete[] p1;
    return 0;
}

2 个答案:

答案 0 :(得分:2)

下面:

*p1[i].display();

您正在调用返回display的成员函数void并尝试取消引用该内容。

答案 1 :(得分:1)

您需要更改:

*p1[i]

要:

p1[i]