c++ - 前向声明和 typeid

标签 c++ gcc declaration forward-declaration typeid

我想根据子类 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/

相关文章:

c++ - 在没有 IDE 的情况下编译单个文件,c++

c++ - 为什么编译器不针对同一翻译单元中的 ODR 违规发出警告

c - 为什么 GCC 分配它不使用的堆栈空间?

javascript - 如何在对象中正确声明对象的 Javascript 数组

c++ - 如何用模板类型初始化成员变量数组?

c++ - 在给定时间内将频率从 f1 缓慢上升到 f2 的正弦波

c++ -/用户/rstu/workspace/.../main.cpp :38:13: No matching conversion for C-style cast from 'void' to 'std::__1::basic_string<char>'

在 C 中创建文件

c - Linux i386 上的 va_arg 错误

variables - 多个文件的声明和全局引用变量