简体   繁体   English

内部类和封闭类的单独定义

[英]Separate definition of inner class and enclosing class

What is the proper way to separate the definition of an inner class and an enclosing class into different header files, if the enclosing class has a member variable which is an instance of the inner class? 如果封闭类的成员变量是内部类的实例,将内部类和封闭类的定义分隔到不同的头文件中的正确方法是什么?

Here is the header of Outer (the enclosing class): 这是Outer (封闭类)的头:

//outer.h
#ifndef OUTER_H_INCLUDED
#define OUTER_H_INCLUDED

#include "inner.h"

class Outer
{
    class Inner;

public:
    /* public member functions */

private:        
    Inner inner_instance;
};

#endif

And the header of Inner : Inner的标题:

//inner.h
#ifndef INNER_H_INCLUDED
#define INNER_H_INCLUDED

#include "outer.h"

class Outer::Inner
{
    /* definition */
};

#endif

This won't compile. 这不会编译。 The problem is that both classes must see the definitions of each other. 问题在于两个类都必须看到彼此的定义。 Is it possible to break the circular dependency and still keep the definitions separated? 是否有可能打破循环依赖关系并仍将定义分隔开?

No. The best you can do is store a pointer (or perhaps reference) to the inner class instead, which allows Inner to be incomplete. 不能。您所能做的最好是存储指向内部类的指针(或引用),这使Inner不完整。 This is generally known as the pImpl idiom. 这通常被称为pImpl成语。

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

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