C ++嵌套类/转发声明问题 [英] C++ nested class/forward declaration issue

查看:119
本文介绍了C ++嵌套类/转发声明问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以转发声明一个嵌套类,然后将其用作外部类的具体(非指向/引用)数据成员的类型?

Is it possible to forward-declare a nested class, then use it as the type for a concrete (not pointer to/reference to) data member of the outer class?

IE

class Outer;

class Outer::MaybeThisWay   // Error: Outer is undefined
{
};

class Outer
{
 MaybeThisWay x;

 class MaybeThatOtherWay;

 MaybeThatOtherWay y;   // Error: MaybeThatOtherWay is undefined
};


推荐答案

根据你想要做什么,也许你可以在外层使用一个命名空间,而不是一个类。你可以转发声明这样的类没有问题:

Depending on what you're trying to do, maybe you can use a namespace rather than a class on the outer layer. You can forward-declare such a class no problem:

namespace Outer {
   struct Inner; 
};

Outer::Inner* sweets;  // Outer::Inner is incomplete so 
                       // I can only make a pointer to it

如果你的Outer绝对必须是一个类,并且你不能将它化为一个命名空间,那么你将需要Outer在一个完整的类型的上下文中你转发declare Inner。

If your Outer absolutely must be a class, and you can't shoe-horn it into a namespace, then you'll need for Outer to be a complete type in the context where you forward declare Inner.

class Outer
{
   class Inner;  // Inner forward-declared
};  // Outer is fully-defined now

Outer yes;  // Outer is complete, you can make instances of it
Outer::Inner* fun;  // Inner is incomplete, you can only make 
                    // pointers/references to it

class Outer::Inner 
{
};  // now Inner is fully-defined too

Outer::Inner win;  // Now I can make instances of Inner too

这篇关于C ++嵌套类/转发声明问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆