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

gor*_*vix 4 c++

假设我有一个基类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)); }
};
Run Code Online (Sandbox Code Playgroud)

是否可以创建与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)); }
};
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 7

这是1的模板:

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

using B1 = Template<A1>;
Run Code Online (Sandbox Code Playgroud)

您可以使用包装器类,该包装器类使用不同的名称委派成员函数:

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


using C1 = Template<A2Wrapper>;
Run Code Online (Sandbox Code Playgroud)

1即在定义中替换类型。

  • @tyebillion您使用的是C ++ 11或更高版本?如果不是,则使用`typedef`,例如:`typedef Template &lt;A1&gt; B1; ... typedef Template &lt;A2Wrapper&gt; C1;` (2认同)