【问题标题】:Accessing and Altering Vectors through class references通过类引用访问和更改向量
【发布时间】:2012-02-18 02:13:14
【问题描述】:

这是我能解决的最简单的问题,抱歉篇幅太长:

#include <vector>
#include <iostream>

class Bar
{
private:
    std::vector<int> intVector_;
public:
    Bar() {};
    void addInt(int newInt) 
    { 
        intVector_.push_back(newInt); 
        std::cout << intVector_.size() << " "; 
    };
    int getIntVectorSize() { return intVector_.size(); };
};

class Foo
{
private:
    Bar bar_;
public:
    Foo() { bar_ = Bar(); };
    Bar getBar() { return bar_; };
};

int main(char argc, char* argv[])
{
    Foo foo = Foo();
    foo.getBar().addInt(1);
    std::cout << foo.getBar().getIntVectorSize() << " ";
    foo.getBar().addInt(2);
    std::cout << foo.getBar().getIntVectorSize() << " ";
    foo.getBar().addInt(3);
    std::cout << foo.getBar().getIntVectorSize() << " ";
}

我的问题是,在向量中添加一个 int 似乎只持续了addInt() 的持续时间。我的向量大小输出如下所示:

1 0 1 0 1 0

我对 C++ 和所有这些引用/指针业务相当陌生,所以我不知道如何解决这个问题,或者这是否可能。感谢您的帮助!

【问题讨论】:

    标签: c++ reference vector


    【解决方案1】:

    这是因为getBar()返回一个Bar by value,它为函数的每次调用复制bar_,而你正在修改临时的向量。 p>

    您可以通过返回引用来避免这种情况:

    class Foo
    {
    private:
        Bar bar_;
    public:
        Foo() { bar_ = Bar(); }; // you prob. want to use an initialiser list btw.
        Bar& getBar() { return bar_; };
    //     ^ notice the ampersand
    };
    

    这样,对 getBar 的返回值所做的任何修改都将在 bar_ 上完成,而不是在语句末尾被销毁的临时副本。

    【讨论】:

    • 我知道这可能是我在做一些愚蠢的事情。 :( 感谢您的快速回答。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多