抽象基底クラスから5つの派生クラスがあります。 1つの関数がオーバーロードされており、派生クラスごとにが存在します。、それをprint()
としましょう。派生4クラスの例:未知の派生クラスポインタへの基本クラスポインタの変換
Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)
が、私は前にも言ったように、すべての派生クラスは、印刷機能を持っていますが、引数が
Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)
すべてのオブジェクトは
vector<Base*> a
のようなベクトルの内部に格納されているように、異なっています
私はそれらをベクターから取り出し、print関数を呼び出そうとすると、すべての呼び出しはprint(* Base)関数に送られます。型を格納することはできません。どのような考えベクトルから来ている。また、型チェックも許可されていません。
例:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
void print(){cout << "greetings from A" << endl;}
};
class C : public A{
public:
void print(){cout << "greetings from C" << endl;}
};
class D : public A{
public:
void print(){cout << "greetings from D" << endl;}
};
class B : public A{
public:
void print(C* c){c->print();}
void print(A* d){d->print();}
};
int main()
{
D d;
C c;
B b;
vector<A*> a; //B,C,D will be stored inside a vector like this.
a.push_back(&c);
a.push_back(&d);
b.print(a[0]);
b.print(a[1]);
return 0;
}
結果:
greetings from A
greetings from A
望ましい結果:
greetings from C
greetings from A
すべてのクラスが異なる 'print'を持っていますあなたの例では(Bを除く)全てが同じもの(同じパラメータ)を持っています - どちらがどちらですか? – UnholySheep
[visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern)をチェックしてください。 – nefas
しかし、一般にダウンキャストのためには、 'dynamic_cast'を使ってキャストが成功したかどうかを調べる必要があります(ヌル以外の値を返す) – UnholySheep