[英]Advice for getting a pointer to an object from a vector stored inside a class
class Element {
class Point {
private:
double x;
double y;
public:
//getters/setters for x and y
};
private:
std::string name;
std::vector<Point> values;
public:
void insertValue(unsigned int index, double x, double y);
...
};
class Collection {
private:
std::string name;
std::vector<Element> elements;
public:
...
...
Element* elementAt(unsigned int index) const {
return const_cast<Element*>(&elements.at(index));
}
};
What I need is to get an Element in a certain index from the collection to do operations like Element::insertValues
.我需要的是从集合中获取某个索引中的元素来执行Element::insertValues
类的操作。 It is a bad practice doing it as it's done in the Collection::elementAt
method (using const_cast)?这样做是一种不好的做法,因为它在Collection::elementAt
方法中完成(使用 const_cast)? Is it better to remove the const qualifier from the method?从方法中删除 const 限定符会更好吗? I marked the method const since the method itself does not modify the object.我标记了方法 const 因为方法本身不会修改对象。
The usual idiom for this is to have two methods, a const
one and a non- const
one.通常的习惯用法是有两种方法,一种是const
方法,一种是非const
方法。 In this case one returns a const Element *
, and the other one returns an Element *
, keeping everything const-correct.在这种情况下,一个返回一个const Element *
,另一个返回一个Element *
,保持一切 const 正确。
const Element* elementAt(unsigned int index) const {
return &elements.at(index);
}
Element* elementAt(unsigned int index) {
return &elements.at(index);
}
Yes, it is true that this leads to some code duplication.是的,这确实会导致一些代码重复。 Such is life, noone has ever accused C++ of being compact and concise.生活就是这样,从来没有人指责过 C++ 简洁明了。
PS: you didn't ask this, but an even better idiom would be to return a reference, rather than a pointer. PS:你没有问这个,但一个更好的习惯用法是返回一个引用,而不是一个指针。 std::vector::at
returns a reference, why shouldn't your pinch-hitter do the same? std::vector::at
返回一个引用,为什么你的捏击者不应该这样做?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.