C ++循环依赖 - 命名空间vs结构 [英] C++ circular dependency - namespace vs struct

查看:92
本文介绍了C ++循环依赖 - 命名空间vs结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请教育我。为什么这样编译:

Please educate me. Why does this compile:

struct compiles
{
    struct A;
    struct B
    {
        B(const A &a) : member(a.member) { }
        int member;
    };
    struct A
    {
        A(const B &b) : member(b.member) { }
        int member;
    };
};

,但这不会:

namespace doesnt
{
    struct A;
    struct B
    {
        B(const A &a) : member(a.member) { }
        int member;
    };
    struct A
    {
        A(const B &b) : member(b.member) { }
        int member;
    };
}

(在MSVC 9.0中)

(in MSVC 9.0)

推荐答案

在C ++中,类范围是特殊的。任何扩展到或超过类定义的结束的声明将自动扩展到由其成员定义(3.3.6 [basic.scope.class])定义的区域。

In C++, class scope is special. Any declaration that extends to or past then end of the class definition is automatically extended to the regions defined by its member definitions (3.3.6 [basic.scope.class]).

这意味着在第一种情况下, struct A 的第一个声明和 struct A 的完整定义都是在 B 及其构造函数的主体中可见

This means that in the first case both the first declaration of struct A and the full definition of struct A are visible in the body of B and its constructor.

这不适用于命名空间范围,因此在第二个 B 的构造函数中的 a.member 是一个错误,因为 struct A 尚未显示。

This doesn't apply to namespace scope so in the second case a.member in the constructor of B is an error because a definition of struct A isn't yet visible.

这篇关于C ++循环依赖 - 命名空间vs结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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