开发者

C++: making custom class to work like both container and normal class?

开发者 https://www.devze.com 2023-02-13 15:22 出处:网络
I want to have some myObject开发者_JAVA技巧 which will store a collection (vector-like) of SomeOtherObjects (so, being homogeneous, right?), which should be iterable and accessible via (myObject[i]).S

I want to have some myObject开发者_JAVA技巧 which will store a collection (vector-like) of SomeOtherObjects (so, being homogeneous, right?), which should be iterable and accessible via (myObject[i]).SomeOtherObjectField1 but also will have normal members like myObject.doStuff() and myObject.Stuff.

Is there any option to implement such class, or using private std::vector to keep the objects (which I'm trying to avoid - don't like private std:: containers) will be smarter?


Prefer composition over inheritance, if your goal is code reuse. (Inheritance should be used to enable polymorphism, which doesn't seem to be an issue in this case.)


That's looks like the composite design pattern. In short, you have to define the interface of your Object class and derive concrete classes, some being container for others. As said, the composition way is better, but using a common interface is the way to use a 'simple' Object or a 'composite' Object the same way.

my2c


I would use a private std::vector<> and an inline method to return a const reference to it. Why don't you like member std containers?


Often the right approach to structure lies in clarifying the semantics. You need to ask questions like "Is myObject a vector<>?". The answer is probably not. If you then follow the principle that a class does one thing (cohesion), then it follows that syntactic sugar around the vector<> is probably not that good.

It tends to follow that the vector<> is a private member. There is no problem with then returning a const reference to it. Returning a non-const reference would break encapulsation - might as well be public data.

If you wish to have:

(myObject[i]).SomeOtherObjectMethod1();

then that is easy enough to implement through operator[](unsigned index). I suspect if you do want that you are better off being consistent and treating myObject as a container in its own right. This means not providing the const ref accessor to the vector<> and implementing the specific accessor methods you really require. This will make client code much easier to understand.

0

精彩评论

暂无评论...
验证码 换一张
取 消