【问题标题】:Updating vector by passing by reference in constructor通过在构造函数中传递引用来更新向量
【发布时间】:2013-07-19 20:25:43
【问题描述】:

我正在尝试编写一段代码,其中我通过类的构造函数通过引用传递向量并更新类的成员函数中的向量。但是当我回到主函数时,向量中没有发生更新:

// 头文件

 class A{
 private:
        std::vector<T> &x;
 public:
        A(std::vector<T>& x_):x(x_) {}
        int func();
 };

// Cpp文件

int A::func() {
     // process done
     T temp;
     x.push_back(temp);
}

//主函数

int main() {
    std::vector<T> vec;
    A a(vec);
    a.func();
}

我尝试将向量更改为类中的指针而不是引用,但函数运行后向量不会更新。有什么建议可以改变程序吗?

【问题讨论】:

  • 您是否遇到任何编译器错误?另外,能发一下构造函数代码吗?
  • 我没有收到任何错误,但函数运行后向量的大小为 0。我在构造函数中什么都没有。
  • "但是函数运行后向量没有更新"你怎么知道?调试器会这么说吗?还是你写了一些代码来检查?
  • @shunyo,在这类事情上不要太相信调试器。

标签: c++ vector


【解决方案1】:
#include <iostream>   
#include <vector>  
using namespace std;

class A
{
    std::vector<int> &x;
public:
    A(std::vector<int>& x_):x(x_) {}
    int func();
};

int A::func(){
    int temp=0;
    x.push_back(temp);
    return 0;
}

int main(){
    std::vector<int> vec;
    A a(vec);
    a.func();
    return 0;
}

一切正常,vec 已更改。我想你还有一个你甚至不知道的问题或错误。

【讨论】:

  • 它的工作。调试器没有正确更新。感谢您的检查。
猜你喜欢
  • 1970-01-01
  • 2012-03-19
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
相关资源
最近更新 更多