简体   繁体   English

为什么我不能在我的矢量中添加项目?

[英]Why can't I add items into my vector?

I have the following code in one class: 我在一个类中有以下代码:

    class A
    {
        std::vector<Parameter*> params;
        std::vector<Parameter*> getParamVector() {return params;}
        void addOneParam(Parameter* param)
        {
            params.push_back(param);
        }
    }

In another class, class B , I try to add items into the params vector by doing this: 在另一个类B类中 ,我尝试通过执行以下操作将项添加到params向量中:

classA_Ptr->getParamVector().push_back(aParamPtr);

But the params vector's size still 0, after above call. 但是在上面调用之后, 参数矢量的大小仍为0。

I have to add above addOneParams(Parameter* param) method to add items into the params vector. 我必须添加上面的addOneParams(Parameter* param)方法来将项添加到params向量中。 Why? 为什么?

getParamVector() returns a copy of params . getParamVector()返回params副本 So when you push_back onto it, you're adding to a temporary vector that gets deleted right away. 因此,当你将push_back添加到它上面时,你会添加一个立即被删除的临时vector That in no way affects params 's size. 这绝不会影响params的大小。

If you want to be able to do this via getParamVector() , you'll have to return a reference to params instead: 如果您希望能够通过getParamVector()执行此操作,则必须返回对params引用

std::vector<Parameter*>& getParamVector() {return params;}
                      ^^^

You should return either by reference or pointer as pointed out. 你应该通过引用或指针返回指出。

std::vector<Parameter*>& getParamVector() { return params; }

or 要么

std::vector<Parameter*>* getParamVector() { return &params; }

But, here is the real question: if you already have a method that can add one parameter, why do you need to call getParamVector().push_back(). 但是,这是一个真正的问题:如果你已经有一个可以添加一个参数的方法,为什么需要调用getParamVector()。push_back()。

Instead, you could just do classA_ptr->addOneParam(p). 相反,你可以做classA_ptr-> addOneParam(p)。

EDIT: To me addOneParam() enforces data hiding better than getting a reference/pointer to the internal vector. 编辑:对我来说,addOneParam()强制数据隐藏比获取内部向量的引用/指针更好。

If the data structure to store the parameters changes, the caller will need to be modified as well. 如果存储参数的数据结构发生变化,则还需要修改调用者。

With addOneParam(), the caller is insulated. 使用addOneParam(),调用者是绝缘的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM