I Klasse B haben, die von A. erbtÜberprüfen des Objekttypen in C++ 11
class A
{
};
class B : public A
{
};
Und ich habe drei Objekte.
A* a = new A();
A* a2 = new B();
B* b = new B();
Ich möchte, wenn ein Scheck Objekt vom Typ A ist, A2 ist Objekt vom Typ B (nicht A), und b Objekt vom Typ B.
habe ich versuchte, typisierte Vergleich, aber Es gibt mir keine richtige Antwort.
cout << (typeid(*a) == typeid(A)) << endl; // -> 1
cout << (typeid(*a2) == typeid(A)) << endl; // -> 1
cout << (typeid(*b) == typeid(A)) << endl; // -> 0
cout << (typeid(*a) == typeid(B)) << endl; // -> 0
cout << (typeid(*a2) == typeid(B)) << endl; // -> 0
cout << (typeid(*b) == typeid(B)) << endl; // -> 1
Ich habe versucht, dynamische Casting, aber ich habe kompilieren Fehler.
B* derived = dynamic_cast<B*>(a);
if (derived) {
cout << "a is B";
}
derived = dynamic_cast<B*>(a2);
if (derived) {
cout << "a2 is B";
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B";
}
typename.cpp: In function 'int main(int, char**)':
typename.cpp:27:36: error: cannot dynamic_cast 'a' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
B* derived = dynamic_cast<B*>(a);
^
typename.cpp:31:34: error: cannot dynamic_cast 'a2' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
derived = dynamic_cast<B*>(a2);
Ich habe statische Casting verwendet, aber ich habe die Antwort falsch.
B* derived = static_cast<B*>(a);
if (derived) {
cout << "a is B"; // -> YES
}
derived = static_cast<B*>(a2);
if (derived) {
cout << "a2 is B"; // -> YES
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B"; // -> YES
}
Wie kann ich den Objekttyp in C++11 korrekt identifizieren?
'* a' ist vom Typ' A' und '* b' ist vom Typ' B' für ihre Deklaration. –
Dynamic Cast funktioniert nur mit virtual, aber Ihr Code hat keine virtuelle Funktion. –
Beste Minimallösung ähnlich wie Ihr Code: http://coliru.stacked-crooked.com/view?id=7150bf0db7988cf1d2988aba99c72392-3b440a87a52fe2ae7c853c82f4c5144f – chris