C++ class that can hold one of a set of classes that all inherit from a common class -


What are the methods in C ++ to handle a class that are owned by another class example, where it Which of the many classes might possibly be possible, all of which are derived from a normal class?

Example:

  class items {// common ancestor, which is not directly public: int size; } Category ItemWidget: Public Items {Possible Grade 1 Public: Integ Height; Integer width } Class item: text: public item {/ possible class 2 studs :: string text; }   

Assume that there is also a class container , each of which has the same item, and only interested in any item at any one time When they are taking it out of the container, also say that the items are made only in containers, they are made only for the purpose of putting them in the container.

What are the different ways of this structure? We can make an indicator in the container for the contained items, and then after the container constructor argue how the item is new to the call, and it will stick the item in all the heaps. Is there a way to store items in the stack with the container, and would it have any advantage?

Does this matter if the containers and items are irreversible, and we know everything about them, the moment of creation, and they will never be changed?

A correct solution looks like this:

  class containers {public : / * Ctor, accessor * / private: std :: unique_ptr & lt; Items & gt; item; };   

If you have an old compiler, you can use std :: auto_ptr instead.

The Smart Pointer ensures strict ownership of the item by the container ( You can make it a plain indicator and create your own destructor / assignment session / copy CTOR / move CTRO / Transfer Assignment session / Etc., but unique_ptr therefore ... )

Why do you need to use a pointer, only a plain Structure?

, then you must know the exact class that is to be. You can not present polymorphisms except for all the container objects should be the same size, and derivative classes of items may vary.

And if

then you need a number of forms of container because the stuff is stored because each container It will be of different size, so this is a different category. Your best shot is:

  struct IContainer {virtual items & amp; GetItem () = 0; }; Template & lt; Typename ItemType & gt; Structure Container: IContainer {Virtual Items & amp; GetItem () {return m_item; } Private: Type the item type m_item; };    

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -