所以我做了两个课程:
class Husky{
private:
int age;
int weight;
public:
//Usual Constructor, set, get functions here
//......
void foo(); //<-----This is the problem function. In here, I change the weight variable.
}
这是第二堂课:
class Dog{
private:
vector<Husky> h;
public:
Husky getHusky(int index); //Returns the Husky element at the index given.
void setHusky(Husky x){h.push_back(x);} //Adds a Husky element to the 'h' array.
}
在我的主要:
int main(){
//Note: the initialized value of `weight` is 0.
Husky p;
p.foo();
cout << p.getWeight() << endl; //This couts 5. foo() DID change 'weight'.
Dog g;
Husky s;
g.push_back(s);
g.getHusky(0).foo();
cout << g.getHusky(0).getWeight() << endl; //This couts 0. foo() DID NOT change 'weight'.
// Why did this not print out 5?
}
请给我一些线索或其他东西,指出我正确的方向。
答案 0 :(得分:4)
Dog::getHusky()
正在返回所请求的Husky
的副本,因为您要按值返回它。然后,您在副本上而不是在原始上调用foo()
。这就是你看到你所看到的结果的原因。
解决方案是更改getHusky()
以通过引用而不是按值返回请求的Huskey
,例如:
Husky& getHusky(int index);
Husky& Dog::getHusky(int index) { return h[index]; }
请注意返回类型附加的&
。