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)
{
开发者_StackOverflow社区 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.)
In coupling with the earlier response, you'll also want to turn your getter into a pass-by-reference (as a pass-by-copy can be slower):
const vector<test *> &getV(){return test1;} //This will provide a read-only reference to your vector.
精彩评论