gpt4 book ai didi

c++ - 是否可以换出 C++ 中的基类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:20 26 4
gpt4 key购买 nike

假设我有一个基类 A1 和派生类 B1 和 B2。例如(人为的):

class A1
{
public:
int foo(int input);
};

class B1: public A1
{
public:
int bar(int input) { return foo(input); }
};

class B2: public A1
{
public:
int bar(int input) { return foo(foo(input)); }
};

是否可以创建与 B1 和 B2 相同但派生自 A2 而不是 A1 的类 C1 和 C2,而不必重新定义“B”?即,我只想将“foo”换成 C1 和 C2 中的另一个函数,而无需重新定义如下:

class A2
{
public:
int newFoo(int input);
};

class C1: public A2
{
public:
int bar(int input) { return newFoo(input); }
};

class C2: public A2
{
public:
int bar(int input) { return newFoo(newFoo(input)); }
};

最佳答案

1 是模板的用途:

template<class T>
struct Template : T
{
int bar(int input) { return this->foo(input); }
};

using B1 = Template<A1>;

您可以使用包装类来委托(delegate)具有不同名称的成员函数:

struct A2Wrapper : A2 {
int foo(int input) { return newfoo(input); }
};


using C1 = Template<A2Wrapper>;

1 即替换定义中的类型。

关于c++ - 是否可以换出 C++ 中的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55561694/

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