我最近遇到了这样的情况:
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;
任何想法?我最近遇到了这样的情况:
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; class C :: D;
谷歌把我带到了这里。 :-\ - franji1class 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) { }
};
如果存在不平稳的复杂构造函数或其他特殊成员函数,这种技术可能会带来更多麻烦。我可以想象某些模板魔法会出现问题。
但在我这个非常简单的情况下,它似乎起作用了。
using basename::basename;
来继承构造函数,因此不会出现复杂构造函数的问题。 - Xeotypedef
。 - ridderhoffclass 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>()
{
// ...
}
但是:
所以,是的,这是一种权衡……
class CD {
};
class C {
public:
using D = CD;
};
class CD;
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;
}
这将是一个解决方法(至少对于问题描述中的问题 - 而不是实际问题,即当无法控制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.h 中使用一个嵌套类 others::A::Nested,而该文件不在我们的控制范围内。
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();
}
a::b
被编译器同样地处理,无论a
是类还是命名空间。 - Mariusz Jaskółka