简体   繁体   中英

How can I create getter and setter for vector in C++?

I declared vector<test*> test1; as a private, and I'd like to create getter and setter for this. I tried,

void setV(vector<test*> test1)
{
    test1 = test1;
}

vector<test*> getV()
{
    return test1;
}

It works, but it works very strange. Is there another way to do it?

Thanks

Look at the assignment statement in setV :

test1 = test1;

The private variable test1 is shadowed by the function parameter of the same name, and you're assigning that parameter to itself.

You should define setV like this:

void setV(vector<test*> const &newTest1) {
  test1 = newTest1;
}

That way you're really assigning the parameter to the private variable, and using a const reference for the parameter avoids an unnecessary temporary copy.


Also, you should define getV as const , and returning a const reference:

vector<test*> const &getV() const {
  return test1;
}

That way it can be called on a const instance of your class, and it avoids making an unnecessary copy for the return value.

(You can also define another getV , without the const s, if you want the caller to be able to modify the vector of a non-const instance of your class.)

与先前的响应配合使用时,您还希望将getter转换为引用传递(因为传递副本的速度可能较慢):

const vector<test *> &getV(){return test1;} //This will provide a read-only reference to your vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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