简体   繁体   English

相互关联的 C++ 类中多态性的最佳实践?

[英]Best practice for polymorphism in interelated C++ classes?

I have a couple of interrelated classes that will be used by multiple different algorithms我有几个相互关联的类,它们将被多种不同的算法使用

Example:例子:

struct B;

struct A {
    B* parent;
};

struct B {
    std::vector<A*> children;
};

Each algorithm may want to specialize these classes based on what they are doing with them, so presumably we they should derive from A and B每个算法可能想要根据它们对它们做什么来专门化这些类,所以大概我们应该从 A 和 B 派生

struct Aderived : A {...};
struct Bderived : B {...};

but methods in Aderived will want to treat parent as Bderived* (to access methods or members added by Bderived ) and Bderived will want to treat the elements of children as Aderived* .但是Aderived方法希望将parent视为Bderived* (以访问Bderived添加的方法或成员),而Bderived将希望将children的元素视为Aderived*

1) Is there a good way for methods in Aderived and Bderived to avoid having to do static casts on parent and children every time they want to access a method of Bderived and Aderived , respectively. 1) 是否有一个很好的方法可以让AderivedBderived中的方法避免在parentchildren每次想要访问BderivedAderived的方法时都必须对他们进行静态转换。

2) How would you even get something like this to compile anyways since you can't forward declare that a class is derived from another... 2)无论如何,你怎么会得到这样的东西来编译,因为你不能转发声明一个类是从另一个类派生的......

struct Aderived : public A {
    int a;
    void x() { static_cast<Bderived*>(b)->b = 1; }   // ERROR
};

struct Bderived : public B {
    int b;
    void x() { static_cast<Aderived*>(avec.back())->a = 1; }
};

define A and B as templates:将 A 和 B 定义为模板:

template < class T1 >
struct A
{
    T1* parent;
};

template < class T2 >
struct B 
{
    std::vector < T2* > children;
};

and while inheritance go for:而继承则是:

struct Aderived : public A < Bderived >
{
  // ...
};

struct Bderived : public B < Aderived >
{
  //...
};

Just declare the member functions of A that cast B* to Bderived* and define them after defining Bderived :只需声明A的成员函数,将B*Bderived*并在定义Bderived后定义Bderived

struct Aderived : public A {
    int a;
    void x();
};

struct Bderived : public B {
    int b;
    void x() { static_cast<Aderived*>(avec.back())->a = 1; }
};

inline void Aderived::x() { static_cast<Bderived*>(b)->b = 1; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM