gpt4 book ai didi

c++ - C++ 中最接近于追溯定义已定义类的父类(super class)的方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 12:40:58 29 4
gpt4 key购买 nike

假设我有课

class A {
protected:
int x,y;
double z,w;

public:
void foo();
void bar();
void baz();
};

在我的代码和其他人的代码中定义和使用。现在,我想写一些库,它可以很好地对 A 进行操作,但它实际上更通用,并且能够操作:

class B {
protected:
int y;
double z;

public:
void bar();
};

我确实希望我的库是通用的,所以我定义了一个 B 类,这就是它的 API 所采用的。

我希望能够告诉编译器——不是在我不再控制的 A 的定义中,而是在其他地方,可能在 B 的定义中:

Look, please try to think of B as a superclass of A. Thus, in particular, lay it out in memory so that if I reinterpret an A* as a B*, my code expecting B*s would work. And please then actually accept A* as a B* (and A& as a B& etc.).

在 C++ 中,我们可以用另一种方式做到这一点,即如果 B 是我们无法控制的类,我们可以使用 class A 执行“子类化已知类”操作:public B { ... };而且我知道 C++ 没有相反的机制——“通过新的 B 类对已知的 A 类进行父类(super class)化”。我的问题是 - 这种机制最接近的可实现近似值是什么?

注意事项:

  • 这都是严格的编译时,而不是运行时。
  • class A 可以有没有的变化。我只能修改 B 的定义和知道 AB 的代码。其他人仍然会使用 A 类,如果我希望我的代码与他们的代码交互,我也会这样做。
  • 这最好是“可扩展”到多个父类(super class)。所以也许我也有 class C { protected: int x;双w;公共(public):无效 baz(); } 的行为也应该类似于 A 的父类(super class)。

最佳答案

您可以执行以下操作:

class C
{
struct Interface
{
virtual void bar() = 0;
virtual ~Interface(){}
};

template <class T>
struct Interfacer : Interface
{
T t;
Interfacer(T t):t(t){}
void bar() { t.bar(); }
};

std::unique_ptr<Interface> interface;

public:
template <class T>
C(const T & t): interface(new Interfacer<T>(t)){}
void bar() { interface->bar(); }
};

这个想法是在幕后使用类型删除(即 InterfaceInterfacer<T> 类)以允许 C采取任何你可以调用bar打开,然后您的库将采用 C 类型的对象.

关于c++ - C++ 中最接近于追溯定义已定义类的父类(super class)的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329583/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com