【问题标题】:how do i initialize a public variable in a public class method如何在公共类方法中初始化公共变量
【发布时间】:2020-03-27 12:42:35
【问题描述】:

我有一个公共类,我在其中创建了一个数组,这个数组从构造函数中获取它的大小,并且需要在其他函数中使用(包括 int main)。因此变量必须是公开的。我的代码看起来是这样的:

class myclass {
    public:
    int parameter1;
    int parameter2;
    myclass(int p, int p2) {
        parameter1 = p;
        parameter2 = p2;
    }
    void makeArray() {
        int array[parameter1][parameter2]; //I want this array to be public as the next method needs access to it
    }
    void otherFunction() {
        array[1][2] = 5; //just an example of what i need to do
    }
}

【问题讨论】:

    标签: c++ arrays access-specifier


    【解决方案1】:

    这是做同样事情的更优化的方式:

    class myclass {
        public:
        int parameter1;
        int parameter2;
        int *array;
        myclass(int p1, int p2) {
            parameter1 = p1;
            parameter2 = p2;
        }
        void makeArray() {
            array = new int[parameter1*parameter2];
        }
        void otherFunction() {
            // ary[i][j] is then rewritten as ary[i*sizeY+j]
            array[1*parameter2+2] = 5;
        }
    };
    int main()
    {
        int sizeX = 5;
        int sizeY = 5;
    
        myclass m1(sizeX,sizeY);
        m1.makeArray();
        m1.otherFunction();
        cout << m1.array[1*sizeY+2] << endl;
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      查看如何使用指针和动态内存..

      做你想做的事情是这样的:

      class myclass {
          public:
          int parameter1;
          int parameter2;
          int **a;
      
          myclass(int p, int p2) {
              parameter1 = p;
              parameter2 = p2;
              a = nullptr;
          }
      
          ~myclass() {
              // TODO: delete "a"
          }
      
          void makeArray() {
              // TODO: delete "a" if it has already been allocated
      
              a = new *int[parameter1];
              for (int i = 0; i < parameter1; ++i) {
                a[i] = new int[parameter2];
              }
          }
      
          void otherFunction() {
              // TODO: check that "a" has already been allocated
              a[1][2] = 5; //just an example of what i need to do
          }
      }
      

      你也可以在构造函数中分配数组,因为你已经传入了必要的信息。

      【讨论】:

      • 为什么建议使用指针和手动分配内存?至少使用std::vector&lt;std::vector&lt;int&gt;&gt;,这样您就不必处理那个令人头疼的问题了。
      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2015-12-17
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多