我想根据子类 B
的类型检查父类(super class) A
的类型(使用父类(super class) A
内部的方法) ,这样 B
将继承它)。
这是我认为的技巧(即使用前向声明):
#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’
我该如何解决这个问题?
最佳答案
我认为您试图解决的问题通过虚拟方法可以更好地处理:
class A
{
public:
virtual bool Check() { return false; };
}
class B : public A
{
public:
// override A::Check()
virtual bool Check() { return true; };
}
基类 A 中的方法不需要知道该对象是否“真正”是 A 还是 B。这违反了基本的面向对象设计原则。如果当对象是 B 时需要更改行为,则应在 B 中定义该行为并通过虚拟方法调用来处理。
关于c++ - 前向声明和 typeid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1915759/