0
我從抽象基類有5個派生類。 一個函數被重載,它存在於每個派生類中的,我們將其命名爲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
當我從矢量中取出其中一個並嘗試調用打印函數時,所有的調用都被指向打印(* Base)函數。我不允許存儲這些類型,因此沒有任何想法來自vector.Also,類型檢查也是不允許的。
一個例子:
#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
查看[訪問者模式](https://en.wikipedia.org/wiki/Visitor_pattern) – nefas
但是,通常對於向下轉換,您應該使用'dynamic_cast'並檢查轉換是否成功(返回非空值) – UnholySheep