私はいくつかの抽象基底クラスを持ちたいと思っています。複数のクラスから継承しています。追加のクラスを宣言することなくオーバーライドされます。いくつかのデザインパターンを介してこれを実現するための方法がある場合複数の継承とオプションの関数のオーバーライドに関する推奨事項が必要です
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
、または:
#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;
}
理論的には、出力は次のようになります。私はここに私が達成しようとしているものの例をあげます私は悪いアプローチを使用しています、私に教えてください。私はC++ 11を使用しています。
このようなものは多態的に使用できますか?たとえば、あるオブジェクト 'shared_ptr' 'とオブジェクト' shared_ptr > 'を作成した場合、その両方を' list >> 'に格納できますか?派生バージョンを 'C 'に変換するには、Cクラスで何が必要なのかよく分かりません。 –
George
@George - いいえ、テンプレートを使うか、明示的に(あなたの質問のように) 'C 'と 'C'は多態性の関係にありません。 –
StoryTeller
@George - しかし、それらのクラスはすべて、 'B *'のコンテナまたは 'A *'のコンテナに入れることができます。 – StoryTeller