2014-01-30 105 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()) –