简体   繁体   English

如何在不与好友友好或不声明指针的情况下在类主体中向前声明未嵌套的类

[英]How to forward-declare unnested class in a class body without befriending or declaring pointer

I know two ways of declaring unnested class inside a class body. 我知道在类主体中声明未嵌套类的两种方法。

First is: 首先是:

class A
{
    friend class B; // B is forward-declared + friend
};

And the second is: 第二个是:

class A
{
    class B* ptr; // B is forward-declared + pointer
};

It's possible to forward-declare a class outside the class body, but for certain reason let's forget about this option; 可以在类主体之外预先声明一个类,但是由于某些原因,让我们忘记此选项;

So, I would like to make possible to declare such member: 因此,我想声明这样的成员:

class A
{
    /* somehow declare B in the body*/
    B* getInstanceB();
};

It's worth to mention, that: With declaring a pointer: 值得一提的是:通过声明指针:

class A
{
    class B* pointer;
    B* getInstanceB(); //fine
};

With friend declaration: 用朋友声明:

class A
{
    friend class B;
    B* getInstanceB(); //GCC 5.3.0 issues error, MSVC compiles
};

I deeply regret that there is no such forward-declaring syntax like: 我很遗憾没有这样的前向声明语法:

class ::[optional-namespace::]ClassName ; class ::[optional-namespace::]ClassName ;

which would distinguish nested class forward-declaration from unnested class forward-declaration. 这将区分嵌套类的正向声明和未嵌套的类的正向声明。 Is it possible to do that in current standard in some other way? 是否可以通过其他方式在当前标准中执行此操作?

To forward-declare a class named B inside the class definition of A without having that class be nested within A , you can do something like the following: 要在A的类定义内向前声明一个名为B的类,而又不将该类嵌套在A ,则可以执行以下操作:

class A {
    typedef class B B;
    // do something with B
};

An explanation can be found here . 可以在这里找到解释。

A demonstration that this actually does work: http://coliru.stacked-crooked.com/a/27913ce45a572d36 实际可行的演示: http : //coliru.stacked-crooked.com/a/27913ce45a572d36

So what you are trying to do is have an instance of a class within another class but have the definition after the "container class"? 那么,您想要做的是在另一个类中有一个类的实例,但是在“容器类”之后有定义?

//forward declaration of B
class B;

class A
{
  public:
    B* getInstanceB();

  private:
     B b_;

};

B* A::getInstanceB()
{
   return &b_;
}

//implementation of B
class B{};

like this? 像这样?

HTH 高温超导

I deeply regret that there is no such forward-declaring syntax like: 我很遗憾没有这样的前向声明语法:

 class ::[optional-namespace::]ClassName; 

which would distinguish nested class forward-declaration from unnested class forward-declaration. 这将区分嵌套类的正向声明和未嵌套的类的正向声明。 Is it possible to do that in current standard in some other way? 是否可以通过其他方式在当前标准中执行此操作?

No, I don't think there is. 不,我认为没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM