Push_back 私有向量有 2 种方法,其中一种不起作用
我有一个带有私有双打向量的类。 为了访问或修改这些值,首先我使用了诸如
void classA::pushVector(double i)
{
this->vector.push_back(i);
}
double classA::getVector(int i)
{
return vector[i];
}
This 之类的方法,工作了一段时间,直到我发现我必须重载很多运算符来满足我的需要,所以我尝试将其更改为直接获取和设置向量现在
void classA::setVector(vector<double> vector)
{
this->vector = vector;
}
vector<double> classA::getVector()
{
return vector;
}
,假设有一个 classB,它有一个私有的 classA 元素,该元素也有用于读取和写入的 get 和 set 方法。问题是当我试图将一个值推回到 A 类中的结束向量时。
void classB::setFirstValue(double first)
{
this->getClassA().getVector().push_back(first);
}
这对向量绝对没有任何作用。它保持不变,我不明白为什么......有什么想法吗?
I have a class with a private vector of doubles.
To access or modify these values, at first I used methods such as
void classA::pushVector(double i)
{
this->vector.push_back(i);
}
double classA::getVector(int i)
{
return vector[i];
}
This worked for a while until I found I would have to overload a lot of operators for what I needed, so I tried to change it to get and set the vector directly instead of the values, i.e.
void classA::setVector(vector<double> vector)
{
this->vector = vector;
}
vector<double> classA::getVector()
{
return vector;
}
Now, say there is a classB, which has a private classA element, which also has get and set methods to read and write. The problem was when I tried to push back a value to the end vector in classA.
void classB::setFirstValue(double first)
{
this->getClassA().getVector().push_back(first);
}
This does absolutely nothing to the vector. It remains unchanged and I can't figure out why... Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将在 getVector() 中按值返回向量。这意味着在您的调用“this->getClassA().getVector().push_back(first);”中,您复制向量,然后将元素推送到副本上。然后该副本立即被丢弃。
为了让它按照您想要的方式工作,您需要通过引用返回向量。您的方法将如下所示:
“vector & classA::getVector()”
You are returning the vector by value in your getVector(). This means that in your call "this->getClassA().getVector().push_back(first);", you copy the vector, then you push the element on the copy. The copy is then immediately discarded.
In order to get it work the way you want, you need to return the vector by reference. Your method will look like:
"vector & classA::getVector()"
在此方法中:
您正在传递向量的副本。要传递实际的向量,您需要一个引用:
并且类中的向量变量必须是一个指针。
这一切对我来说看起来都很不受欢迎——我会重新思考你们的班级实际上在做什么。类管理向量比维护指向类外部向量的指针更有意义。如果您需要重新实现所有类方法,也许您根本不需要类,而只需要一个向量。
In this method:
you are passing a copy of the vector. To pass the actual vector, you need a reference:
and the vector variable in your class will have to be a pointer.
This all looks pretty undesirable to me - I would rethink what your class is actually doing. It makes much more sense for the class to manage the vector than for it to maintain a pointer to one outside the class. and if you need to re-implement all the class methods, maybe you don't need te class at all, but just a vector.