为什么我的程序没有更改结构变量中的值?

时间:2019-10-12 17:56:24

标签: c++

好吧,我已经输入了这个简单的程序:

#include <iostream>
using namespace std;
struct workers
{
   char workername[55];
   int workernumb;
   float workerwage;
};
void changewage(workers worker1);
void show(workers worker1);
int main() // Defines all the workers profile and then call 'void show' to show the selected worker profile, is working well.
{
   workers worker1=
   {
       "The name of the worker goes here",
        The number of the worker goes here,
        The wage of the worker goes here
    };
   cout << "Worker data:" << endl;
   show(worker1);
   changewage(worker1);
   cout << "New worker wage:" << endl;
   show(worker1);
   return 0;
}
void show(workers worker1) // Program that shows the workers profile, is also working fine.

{
   cout << "Name: " << worker1.workername << endl;
   cout << "Number: " << worker1.workernumb<< endl;
   cout << "Wage: " << worker1.workerwage<< endl;
}

void changewage(workers worker1) // Program that changes the wage of a selected worker, here it is not working fine.

{
    float newwage;
    cin >> newwage;
    newwage=worker1.workerwage;
}

它应该用于显示工人的个人资料并更改他的工资,当我键入新工资时,应该更改“ worker1.workerwage”,同时还要更改“ void show”中的单位,然后再更改配置文件将显示新工人的工资。 问题在于它仍显示先前的值,并且未更改任何内容。 附注:该程序本身运行良好,唯一的问题是它的功能之一无法按照我想要的方式运行。而且,正如您所看到的,我是学习c ++的初学者,如果我犯了一些错误,对不起...

1 个答案:

答案 0 :(得分:0)

如果要修改对象,则必须通过引用。

==

代码不起作用的原因是因为复制了worker1并修改了副本,所以复制的对象位于函数的本地,并且当函数返回复制的对象时死亡。