继承在子节点中初始化的数组

woo*_*ie1 5 c++ arrays inheritance

我正在寻找做这样事情的最好方法:

class variable{
    protected:
    variable()
    int convert[][]
}

class weight: variable{
    public:
    weight(){
        convert = {{1,2},{1,3},{2,5}}
    }
Run Code Online (Sandbox Code Playgroud)

现在我知道我不能这样做,因为我必须提前声明数组大小.我有很多类都继承自基类变量,而变量有一个使用convert的函数,所以不要分别在每一个中声明转换.对于每个类,数组长度将保持不变,因此使用列表似乎是不必要的.你有什么建议.

非常感谢.

Naw*_*waz 4

有几种选择。

  • 使用std::vector
  • 或者使用std::array(仅在 C++11 中可用)
  • 或者做这样的事情:

    template<size_t M, size_t N>
    class variable{
       protected:
         int convert[M][N];
    };
    
    class weight: variable<3,2>{
    public:.
     weight(){
       //convert = {{1,2},{1,3},{2,5}} //you cannot do this for arrays
       //but you can do this:
       int temp[3][2] = {{1,2},{1,3},{2,5}};
       std::copy(&temp[0][0], &temp[0][0] + (3*2), &convert[0][0]);
    };
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者您也可以使用std::vectorstd::array与模板一起使用。