서브 클래스 B
의 유형에 대해 수퍼 클래스 A
의 유형을 확인하고 싶습니다 (수퍼 클래스 A
의 메소드를 사용하여 B
이이를 상속 함). 전달 선언 및 typeid
#include <iostream>
#include <typeinfo>
using namespace std;
class B;
class A {
public:
int i_;
void Check() {
if (typeid (*this) == typeid (B))
cout << "True: Same type as B." << endl;
else
cout << "False: Not the same type as B." << endl;
}
};
class B : public A {
public:
double d_;
};
int main() {
A a;
B b;
a.Check(); // should be false
b.Check(); // should be true
return 0;
}
그러나이 코드는 컴파일되지 않습니다 :
는 여기에 (즉, 앞으로 선언의 사용이다) 속임수를 썼는지 생각거야. 오류는 다음과 같습니다.
main.cc: In member function ‘void A::Check()’:
main.cc:12: error: invalid use of incomplete type ‘struct B’
main.cc:6: error: forward declaration of ‘struct B’
이 문제를 어떻게 해결할 수 있습니까?
기본 OOP 원칙을 위반하고 있다고 생각하지 않았습니다. 말할 것도없이 내가하려고했던 것은 효과가 없었습니다. 제안한대로 가상 기능을 사용하여 모든 것을 다시 작성했습니다. 감사합니다. – Jir