结构内部结构:“非法引用非静态成员”错误

时间:2019-05-24 14:20:02

标签: c++ struct constructor

我需要在struct内部创建一个struct。如何正确编码构造函数?我需要分别为A和B创建两个构造函数,还是可以像下面的示例一样仅为A使用一个“外部”构造函数?我的尝试导致C2597错误。

struct A
{
    struct B
    {
        unsigned n;
        int* d;
    };

    A(unsigned c)
    {
        B::n = c; // C2597
        B::d = new int[c]; // C2597
    }
};

3 个答案:

答案 0 :(得分:5)

您需要使B的成员成为静态成员(但在这种情况下,对于Windows来说,整个程序或dll将只有一个值):

struct A
{
    struct B
    {
        static unsigned n;
        static int* d;
    };

    A(unsigned c)
    {
        B::n = c;
        B::d = new int[c];
    }
};

或创建B的实例:

struct A
{
    struct B
    {
        unsigned n;
        int* d;
    };

    A(unsigned c)
    {
        B b;
        b.n = c;
        b.d = new int[c];
    }
};

如果您想让A包含B-那就是您需要做的:

struct A
{
    struct B
    {
        unsigned n;
        int* d;
    } b;

    A(unsigned c)
    {
        b.n = c;
        b.d = new int[c];
    }
};

答案 1 :(得分:3)

您需要一个B实例才能访问成员nd

struct B
{
    unsigned n;
    int* d;
} b; // Create an instance of `B`

A(unsigned c)
{
    b.n = c;
    b.d = new int[c]; // ToDo - you need to release this memory, perhaps in ~B()
}

要么要么将它们设为static

答案 2 :(得分:2)

您没有声明成员,因为代码B中是A类的嵌套类。

您必须声明该类的成员。

struct A
{
    struct B
    {
        unsigned n;
        int* d;
    }; // this is a class-type declaration

    B data; // this is member of class A having type of class B

    A(unsigned c) 
    {
        data.n = c; 
        data.d = new int[c]; 
    }
};