【问题标题】:Struct inside struct: 'Illegal reference to non-static member' error结构内部的结构:“对非静态成员的非法引用”错误
【发布时间】:2019-10-11 04:02:37
【问题描述】:

我需要在结构中创建一个结构。如何正确编码构造函数?我是否需要分别为 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
    }
};

【问题讨论】:

    标签: c++ struct constructor


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • static 也意味着你的程序中只能有一个A 的实例,否则你会泄漏内存。
      【解决方案3】:

      您需要B 的实例 才能访问成员n 和d。

      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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-24
        • 2013-02-05
        相关资源
        最近更新 更多