简体   繁体   English

在函数内部声明的相互C ++类

[英]Mutual C++ classes declared inside of a function

How do I define classes inside of a function so that they "know" about each other? 如何在函数内部定义类,以便它们彼此“了解”? Here is a greatly dumbed down version of what I'm trying to understand. 这是我要了解的内容的精简版。 I'd like to do something like: 我想做类似的事情:

void foo () {

    struct A {
        static void bar () {
            B::hmm();
        }
    };

    struct B {
        static void hmm () {
            A::bar();
        }
    }
}

That doesn't work because A::bar() doesn't know anything about B yet. 那是行不通的,因为A :: bar()尚不了解B。 Outside of a function, I could defer the definition of A::bar() until after B is declared. 在函数之外,我可以将A :: bar()的定义推迟到声明B之后。 Something like: 就像是:

void foo () {

    struct A {
        static void bar ();
    };

    struct B {
        static void hmm () {
            A::bar();
        }
    }

    void A::bar () {
        B::hmm();
    }
}

But that doesn't seem to work inside of a function. 但这似乎在函数内部不起作用。

In lieu of some clever scoping declaration that makes this all work, I'd also welcome a definitive answer saying this is just not possible in C++ (reference please). 除了一些巧妙的作用域声明使所有这些都起作用之外,我还欢迎一个明确的回答,说这在C ++中是不可能的(请参考)。

I know there are other ways to work around this (declaring the classes outside of foo, for instance), so I'm not looking for answers on how to do something similar... 我知道还有其他方法可以解决此问题(例如,在foo外部声明类),因此我不在寻找有关如何执行类似操作的答案...

You don't. 你不知道

Member functions of local classes must be defined inside of the class definition. 局部类的成员函数必须在类定义内定义。

Because the definitions of A::bar() and B::hmm() are mutually dependent and because member functions cannot be forward declared outside of a class definition, there is no way to order the definitions such that this can work. 因为A::bar()B::hmm()是相互依赖的,并且成员函数不能在类定义之外进行前向声明,所以没有办法对这些定义进行排序以使其可以正常工作。

(You said you aren't looking for workarounds, but I'll say anyway that, in my opinion, defining any remotely complex class, more or less multiple classes, inside a function definition, hinders code readability and is a bad idea.) (您说过,您并不是在寻找解决方法,但是我认为无论如何,我认为在函数定义中定义任何远程复杂的类,或多或少的多个类,都会妨碍代码的可读性,这是一个坏主意。)

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

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