【问题标题】:reference to nested class (struct) in header file引用头文件中的嵌套类(结构)
【发布时间】:2021-08-11 02:22:07
【问题描述】:

如果我在类中有这样的嵌套结构:

(a.h file)
class A{
public:
    struct B{...};
};

我想在其他 .h 文件中传递引用 A::B 的参数。我该怎么做? 我想做:

(b.h file)
class B{
    randomMethod(A::B arg0);
};

我听说在 .h 文件中包含其他 .h 文件不是一个好习惯。所以我尝试在B类之前添加一些类声明,但它不起作用。 我试过了:

class A::B;
class B{...}
or 
class A;
class A::B;
class B{...} 

【问题讨论】:

标签: c++ class reference header-files


【解决方案1】:

我听说在 .h 文件中包含其他 .h 文件不是一个好习惯。

您可能误解了,或者您听到了错误的信息。在 headers 中包含 headers 是正常的。

我想在其他 .h 文件中传递引用 A::B 的参数。我该怎么做?

您必须定义声明嵌套类的外部类。最方便且最不容易出错的方法是包含一个定义类的文件。

不过,确实最好尽量减少夹杂物的数量。您可以通过在外部定义另一个嵌套类来避免包含外部类的定义 - 这样它就不再嵌套。您仍然可以在外部类中定义成员类型别名。例如:

namespace A_ns {
    struct B; // declaration only
}

class B {
    // doesn't requre definition of A nor A::B
    return_type randomMethod(A_ns::B arg0);
};

namespace A_ns {
    struct B{}; // defined outside of A

    class A {
    public:
        // type alias instead of nested class
        using B = A_ns::B;
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多