-1

所以我做了两个类:

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?

}

请给我一个线索或一些东西来指引我正确的方向。

4

1 回答 1

4

Dog::getHusky()正在返回请求的副本Husky,因为您按值返回它。然后,您调用foo()的是副本而不是原件。这就是为什么你看到你所看到的结果。

解决方案是更改为通过引用而不是按值getHusky()返回请求,例如:Huskey

Husky& getHusky(int index);

Husky& Dog::getHusky(int index) { return h[index]; }

注意&附加到返回类型。

于 2013-09-21T02:16:39.183 回答