我想对照子类A的类型检查父类(super class)B的类型(在父类(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/

10-15 01:06
查看更多