2014-01-30 72 views
0

这是我的代码,我试图通过询问用户的大小来为对象分配内存。我不知道我哪里错了。编译器给我的错误是"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; 
} 

回答

1

你需要改变:

*p1[i] 

要:

p1[i] 
2

这里:

*p1[i].display();

你调用成员函数display返回void并尝试解除引用。

+0

+1其实正确的答案 - 强调:*(p1 [i] .display()) –