[英]How can I create getter and setter for vector in C++?
I declared vector<test*> test1;
我声明了
vector<test*> test1;
as a private, and I'd like to create getter and setter for this. 作为私有,我想为此创建getter和setter。 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
: 查看
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. 私有变量
test1
被同名的function参数遮盖,并且您正在为其分配参数。
You should define setV
like this: 您应该这样定义
setV
:
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. 这样,您实际上就是将参数分配给私有变量,并且对参数使用
const
引用可以避免不必要的临时复制。
Also, you should define getV
as const
, and returning a const
reference: 另外,您应该将
getV
定义为const
,并返回const
引用:
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. 这样,可以在您的类的
const
实例上调用它,并且避免为返回值创建不必要的副本。
(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.) (如果希望调用者能够修改类的非const实例的向量,则也可以定义另一个不带
const
的getV
。)
与先前的响应配合使用时,您还希望将getter转换为引用传递(因为传递副本的速度可能较慢):
const vector<test *> &getV(){return test1;} //This will provide a read-only reference to your vector.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.