C++ 继承和包含

C++ Inheritance and Includes

我不是 C++ 的新手,但我也绝对不是专家...但是 :)

我正在尝试了解继承的工作原理。我有一个 class 派生自基数 class:

class Base {}

#include "Base.h"
class Derived : public Base {}

在我的基础 class 中,我正在尝试创建一个静态方法,该方法 return 是指向 Derived class 对象的指针:

#include "Derived.h"
class Base {
     static Derived* getDerived();
}

现在我想因为这是一个静态成员,所以我可能能够摆脱它,但我遇到了编译时问题,抱怨 Derived class 不知道 Base 对象是什么,甚至虽然我在 Derived class 中包含了 Base.h。我也知道循环依赖,但是因为我试图 return 一个指向对象的指针,我认为编译器不需要 #include "Derived.h",但它似乎需要。

任何关于为什么这不是要走的路以及我可以做什么的方向将不胜感激!

(我目前在 Java 中这样做)

这是循环引用。

  1. 要使用Class-Base,你需要知道Class-Derived,因为它包含一个带有Class-Derived return的静态函数输入.

  2. 要使用Class-Derived,需要知道Class-Base,因为它是从Class-Base

    [=派生的19=]

是的,对于你的情况(只是 return 指向对象的指针),编译器不需要 #include "Derived.h",它只需要 forward declaration:

class Derived;
class Base {
     static Derived* getDerived();
};

演示:http://ideone.com/ONUHGc

下面的代码回答了你的问题,但是我完全不知道你为什么要这样做

在我看来,您的 base class 的目的是提供一个足以满足您需求的接口,因此 无需任何派生类型的知识.

Base.h

#ifndef BASE_H
#define BASE_H

class Derived; // Forward declaration to avoid including 'Derived.h'

class Base
{
public:
    virtual ~Base() {}

    // Non-static function so that it has access to 'this'
    Derived* getDerived();
};

#endif

Base.cpp

#include "Base.h"

#include "Derived.h"

Derived* Base::getDerived()
{
    return dynamic_cast<Derived*>(this);
}

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include "Base.h"

class Derived : public Base
{
public:
    virtual ~Derived() override {}
};

#endif

main.cpp

#include "Derived.h"

#include <iostream>

int main()
{
    Derived d;
    Base* b = &d;

    std::cout << &d << " : " << b->getDerived() << "\n";

    return 0;
}