我最近遇到了这样的情况:

class A
{
public:
    typedef struct/class {…} B;
…
    C::D *someField;
}

class C
{
public:
    typedef struct/class {…} D;
…
    A::B *someField;
}

通常你可以声明一个类名:

class A;

但是不能前向声明嵌套类型,下面会导致编译错误。

class C::D;

什么好主意吗?


当前回答

这将是一种变通方法(至少对于问题中描述的问题-而不是实际问题,即当无法控制C的定义时):

class C_base {
public:
    class D { }; // definition of C::D
    // can also just be forward declared, if it needs members of A or A::B
};
class A {
public:
    class B { };
    C_base::D *someField; // need to call it C_base::D here
};
class C : public C_base { // inherits C_base::D
public:
    // Danger: Do not redeclare class D here!!
    // Depending on your compiler flags, you may not even get a warning
    // class D { };
    A::B *someField;
};

int main() {
    A a;
    C::D * test = a.someField; // here it can be called C::D
}

其他回答

这可以通过将外部类向前声明为名称空间来实现。

示例:我们必须使用嵌套类others:: a::嵌套在others_a.h中,这是我们无法控制的。

others_a.h

namespace others {
struct A {
    struct Nested {
        Nested(int i) :i(i) {}
        int i{};
        void print() const { std::cout << i << std::endl; }
    };
};
}

my_class.h

#ifndef MY_CLASS_CPP
// A is actually a class
namespace others { namespace A { class Nested; } }
#endif

class MyClass {
public:
    MyClass(int i);
    ~MyClass();
    void print() const;
private:
    std::unique_ptr<others::A::Nested> _aNested;
};

my_class.cpp

#include "others_a.h"
#define MY_CLASS_CPP // Must before include my_class.h
#include "my_class.h"

MyClass::MyClass(int i) :
    _aNested(std::make_unique<others::A::Nested>(i)) {}
MyClass::~MyClass() {}
void MyClass::print() const {
    _aNested->print();
}
class IDontControl
{
    class Nested
    {
        Nested(int i);
    };
};

我需要这样的推荐信:

class IDontControl::Nested; // But this doesn't work.

我的解决方案是:

class IDontControl_Nested; // Forward reference to distinct name.

后来当我可以使用完整的定义时:

#include <idontcontrol.h>

// I defined the forward ref like this:
class IDontControl_Nested : public IDontControl::Nested
{
    // Needed to make a forwarding constructor here
    IDontControl_Nested(int i) : Nested(i) { }
};

如果存在复杂的构造函数或其他不能顺利继承的特殊成员函数,这种技术可能会带来更多麻烦。我可以想象某些模板魔法的反应很糟糕。

但在我这个非常简单的例子中,它似乎是有效的。

如果你真的想避免在头文件中包含讨厌的头文件,你可以这样做:

进行文件:

class MyClass
{
public:
    template<typename ThrowAway>
    void doesStuff();
};

cpp文件

#include "MyClass.hpp"
#include "Annoying-3rd-party.hpp"

template<> void MyClass::doesStuff<This::Is::An::Embedded::Type>()
{
    // ...
}

但之后:

您必须在调用时指定嵌入类型(特别是如果您的函数不接受任何嵌入类型的参数) 函数不能是虚函数(因为它是模板)

所以,是的,权衡……

你做不到,这是c++语言的漏洞。您必须取消嵌套的类中的至少一个。

我不认为这是一个答案,但这是一个有趣的发现: 如果在名为C的名称空间中重复声明结构,那么一切都没问题(至少在gcc中是这样)。 当找到C的类定义时,它似乎会无声地覆盖名称空间C。

namespace C {
    typedef struct {} D;
}

class A
{
public:
 typedef struct/class {...} B;
...
C::D *someField;
}

class C
{
public:
   typedef struct/class {...} D;
...
   A::B *someField;
}