Inherit the array that is initialized in the child

I am looking for a better way to do something like this:

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

class weight: variable{
    public:
    weight(){
        convert = {{1,2},{1,3},{2,5}}
    }

Now I know that I can’t do this, because I have to declare the size of the array in advance. I have many classes, all inheriting from a variable of the base class, and the variable has a function that uses convert, so I do not want to declare the conversion in each separately. For each class, the length of the array will remain constant, so using a list seems unnecessary. What are your suggestions.

Many thanks.

+5
source share
2 answers

There are several options.

  • Use std::vector.
  • Or use std::array(only in 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]);
    };
    
  • std::vector std::array .

+4

, . , "" , " " , . :

class variable {
private:
    virtual std::vector<"your type"> getConvertMatrix() const = 0;

    void someMethodThatNeedsConvertMatrix() {
        // ...
        std::vector<"your type"> convertMatrix = getConvertMatrix();
        // ...
    }
}

class weight : public variable {
private:

    virtual std::vector<"your type"> getConvertMatrix() const {
        // your implementation
        // form vector and return it, or return vector declared as member
    }
}
0

All Articles