【发布时间】:2017-09-20 14:30:11
【问题描述】:
我有一个问题,我想解决一个问题,我希望有一些抽象基类,它继承自多个类,派生可以选择性地覆盖它们的方法,而无需声明额外的类。我将在这里举例说明我想要实现的目标:
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo() = 0;
protected:
A() {}
};
class A1 : public A
{
public:
A1() : A() {}
void foo() { cout << "A1 foo" << endl; };
};
class A2 : public A
{
public:
A2() : A() {}
void foo() { cout << "A2 foo" << endl; };
};
class B
{
public:
virtual void bar() { cout << "B bar: " << endl; }
};
class B1 : public B
{
public:
void bar()
{
cout << "B1 bar wrapper begin" << endl;
B::bar();
cout << "B1 bar wrapper end" << endl;
}
};
/*
???
pure virtual class C
enforce derived classes to inherit something of type A
enforce derived classes to inherit something of type B
class C1 : public A1, either B or B1 ??? templates???
{
}
class C2 : public A2, either B or B1 ??? templates???
{
}
Can this be done without having to define classes CA1B, CA2B, CA1B1, CA2B1, etc.?
*/
int main(int argc, char *argv[])
{
A1 a1;
a1.foo();
A2 a2;
a2.foo();
/*
C1 c1b with type B
C1 c1b1 with type B1
C2 c2b with type B
C2 c2b1 with type B1
put c1b, c1b1, c2b, c2b1 in a list named "combinations"
cout << "Printing combinations" << endl;
for (auto i : combinations)
{
i->foo();
i->bar();
}
*/
return 0;
}
理论上输出是:
A1 foo
A2 foo
Printing combinations
A1 foo
B bar
A1 foo
B1 bar wrapper begin
B bar
B1 bar wrapper end
A2 foo
B bar
A2 foo
B1 bar wrapper begin
B bar
B1 bar wrapper end
如果有办法通过某种设计模式来实现这一点,或者我使用了不好的方法,请告诉我。我正在使用 C++11。
【问题讨论】:
标签: c++ templates inheritance polymorphism overriding