结构内部的结构:"对非静态成员的非法引用"错误



我需要在struct内部创建一个结构。如何正确编码构造函数?我是否需要为A和B分别创建两个构造函数,或者我只能在下面的示例中使用一个"外部"构造函数?我的尝试导致C2597错误。

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

您需要使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];
    }
};

您需要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

您没有声明成员,在您的代码B中是nested 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]; 
    }
};

最新更新