Passing a vector by reference to function, but cha

2019-02-21 20:19发布

问题:

I'm new to C++ so please forgive the noob question. In my program, I pass a vector of "Employee" objects to a function by reference, which calls an Employee member function on each object in the vector, to raise "salary" by "r" percent (in this case 2 percent). I've verified that this is happening by logging the call (the salary is changed within the function), but the changes don't persist...when I print the Employee objects again, the salaries are unchanged. Appreciate any help!

// main.cpp
void raiseAllBy2Percent(vector<Employee> &v)
{
for (int i = 0; i < v.size(); i++)
    {
    Employee e = v[i];
    e.salaryRaise(2);
    }
}

// Employee.cpp
void Employee::salaryRaise(double r)
{
cout << "**salaryRaise called";
_salary += (r/100 * _salary);
cout << "**new salary: " << _salary; // This logs with the change as expected
}

回答1:

You are passing the vector by reference, but at this line:

Employee e = v[i];

you are copying the employee object. Make that a reference too:

Employee &e = v[i];

and it will behave as expected.

(Note that this only works because std::vector::operator[] itself returns a reference, as most standard containers' subscript operator does.)



回答2:

You are not changing the vector content. Instead you assign it to another new Employee object, e and modify that:

Employee e = v[i];
e.salaryRaise(2);

Change this to:

v[i].salaryRaise(2);

This will modify the elements in the vector.



回答3:

You are making a copy of the elements in the vector here:

Employee e = v[i]; // e is a copy of v[i]

You probably mean

v[i].salaryRaise(2);