What is the correct way to let the user access or modify a private container?
Assuming a situation where we have:
// X is a struct
class A {
private:
std::vector<X> _v;
// ... other member variables
public:
A();
// ... other member functions
};
how would I go about defining a member function A::get which returns the X
value of the element with index i? Or how would I go about defining a
member function A::setFieldA that allows me to set the a field of the
struct X?
I came to a, probably very bad, solution myself:
// X is a struct
class A {
private:
std::vector<X> _v;
// ...
public:
A();
X get(std::size_t index);
void setFieldA(std::size_t index, int field_value);
// ...
};
where we use std::size_t to let the user access a specific element.
Q1: Is this an acceptable approach? If not, why?
Q2: What other options would I have to let the user of the class A access
(modifying or not) the inner vector via member functions?
Q2.1: What is the "standard" way of handling this kind of private access
from outside the outer class with STL containers?
Note: I'd like member functions because I need to emit a Qt signal every
time the vector or an element of the vector is modified.
No comments:
Post a Comment