开发者

how to customize the nested class's methods in C++

开发者 https://www.devze.com 2023-03-07 04:29 出处:网络
I have a class A with nested class Inner_vector, class A: { public: class Inner_vector:public Vector { bool append(const class Element& element);

I have a class A with nested class Inner_vector,

class A: 
{
public: 
  class Inner_vector:public Vector
    {
      bool append(const class Element& element);
    };
};
bool A::Inner_vector::append(const class Element& element)
{
   add(element开发者_运维百科);
}

Now I want to derive a child class from A and also customize the "append" and "delete" methods of the inner class "Inner_vector" (mainly to add one new operation), so that the customized operations will be called instead. How could I do it? should I also derive a new nested class inside Child_A from A::Inner_vector as the following code

class Child_A: public A
{
public: 
  class Inner_Child_vector : public A::Inner_vector
    {
      bool append(const class Element& element);
    };
};
bool Child_A::Inner_Child_vector::append(const class Element& element)
{
   A::Inner_vector::append();
   my_new_operation();
}

Or I do not need to derive from A::Inner_vector and directly rewrite it?

I really appreciate any help and comments.


In C++, inner classes are unrelated to the classes containing them except for scoping. So you have to derive the base's inner class in the derived class.


You could always not create another class for inner_vector and have it a protected member in your outer class 'A', class 'A' can then define two virtual functions append and delete.

Which means when you inherit and create 'Child_A' you just define a new behaviour for append and delete. This will require you to extend your inner vector class to give you enough access to its internals that you can create the append and delete behaviours you want from the classes that contain it.

class A 
{
 public: 
  virtual bool append( const class Element& element )
  {
    //  your specific A behaviour
  }     

 protected:
  // std::vector or your own implementation
  std::vector _innerVector;

};

class Derived : public A
{
 public:
  virtual bool append( const class Element& element )
  {
    // derived implementation
  }
};

If this is not possible then you have to derive both classes as they are unrelated.

0

精彩评论

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