2017-09-25 76 views
0

我有两个动态分配的类对象 - 学生和工作人员数组。当用户输入年龄时,我希望根据年龄更新学生阵列或职员阵列的元素。 但我下面的代码不起作用。一旦分配给学生,变量人员不会被重新分配给工作人员。无论我输入的年龄如何,我输入的所有数据都只会发放给学生。我的代码有什么问题?我怎么能有一个变量,并根据条件检查分配一个或其他数组元素?更改动态分配数组中元素的值

#include <iostream> 
using namespace std; 

int main() 
{ 
    class info 
    { 
    public: 
     int unique_id; 
     char* hair_color; 
     int height; 
     int weight; 
    }; 

    class info* student; 
    student = new info[10]; 

    class info* staff; 
    staff = new info[10]; 

    for (int i=0; i<10;i++) 
    { 
     class info& person = student[i]; 

     int age ; 
     cout<< "enter age"<<endl; 
     cin >> age; 

     if(age > 18) 
     { 
      person = staff[i]; // This assignment doesn't work ?? 
     } 
     cout<< "enter unique_id"<<endl; 
     cin >> person.unique_id; 
     cout<< "enter height"<<endl; 
     cin >> person.height; 
     cout<< "enter weight"<<endl; 
     cin >> person.weight; 

    } 

    cout<<" Student "<<student[0].unique_id<<" "<<student[0].height<<"\" "<<student[0].weight<<endl; 
    cout<<" Staff "<<staff[0].unique_id<<" "<<staff[0].height<<"\" "<<staff[0].weight<<endl; 

    return 0; 
} 
+0

看起来像C++代码。如果是这样,请将C++标签添加到您的问题。谢谢! –

+0

如果你有一个引用'int&rx = x;'如果你给这个引用赋新值,例如'rx = 5;',你认为应该发生什么?在你认为分配不起作用的行中发生了什么? –

+0

你不能[重新安置一个参考。](https://stackoverflow.com/questions/7713266/how-can-i-change-the-variable-to-which-ac-reference-refers)这会导致问题@ ArtemyVysotsky暗示。 – user4581301

回答

1

You cannot reseat a reference.一旦它被设置,它的卡在那里和任何企图重新分配参考将被解释为分配给该引用的变量的请求。这意味着

person = staff[i]; 

被实际复制staff[i];person其是用于student[i]别名(另一名称)。 student[i]将继续接收从用户读取的输入。

给出你当前的代码最简单的方法是用一个指针替换引用,该指针可以被重置。

class info* person = &student[i]; // using pointer 

int age ; 
cout<< "enter age"<<endl; 
cin >> age; 

if(age > 18) 
{ 
    person = &staff[i]; // using pointer, but note: nasty bug still here 
         // You may have empty slots in staff 
} 

cout<< "enter unique_id"<<endl; 
cin >> person->unique_id; // note the change from . to -> 
.... 

但有办法解决这个问题。您可以延迟创建引用,直到您知道使用哪个数组。这需要对许多代码进行洗牌,并且如果不小心,仍然会在数组中留下未使用的元素。

幸运的是有一个更好的方法来做到这一点使用std::vector from the C++ Standard Library's container library.

std::vector<info> student; 
std::vector<info> staff; 

for (int i=0; i<10;i++) 
{ 
    info person; // not a pointer. Not a reference. Just a silly old Automatic 

    int age ; 
    cout<< "enter age"<<endl; 
    cin >> age; 

    // gather all of the information in our Automatic variable 
    cout<< "enter unique_id"<<endl; 
    cin >> person.unique_id; 
    cout<< "enter height"<<endl; 
    cin >> person.height; 
    cout<< "enter weight"<<endl; 
    cin >> person.weight; 

    // place the person in the correct vector 
    if(age > 18) 
    { 
     staff.push_back(person); 
    } 
    else 
    { 
     student.push_back(person); 
    } 
}