我會嘗試檢查一個指針作爲參數如下傳遞什麼類型:如何在運行時檢查類型?
#include <iostream>
struct A{};
struct B:A{};
struct C:A{};
C *c = new C;
B *b = new B;
A *a = new A;
void foo (A *a)
{
if(dynamic_cast<B*>(a))
{
std::cout << "Type is B*" << std::endl;
//cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct B*' (source type is not polymorphic)
}
if(dynamic_cast<C*>(a))
{
std::cout << "Type is C*" << std::endl;
//cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct C*' (source type is not polymorphic)
}
}
但甚至不進行編譯。有可能這樣做嗎?我的意思是,確定什麼指針指向我們作爲函數參數傳遞的類型?
「A」中至少需要一個'virtual'函數,最簡單的是聲明一個虛擬析構函數。 –
@πάνταῥεῖ用於什麼?虛擬函數如何幫助我在運行時確定類型?沒有看到...... –
編譯器在這種情況下創建了一個vtable,這對'dynamic_cast'是必需的。 –