假设我有一个基类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)
这是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即在定义中替换类型。