【问题标题】:Inherit an array that is initialised in the child继承在孩子中初始化的数组
【发布时间】:2011-11-13 15:40:32
【问题描述】:

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

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

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

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

非常感谢。

【问题讨论】:

  • 那么,问题出在哪里?从你的描述看不清楚。您需要在不同的派生类中使用不同的数组大小还是什么?
  • 我不太清楚你的问题是什么,但听起来你继承是为了重用,而不是扩展,所以你可能想再看看你的设计,看看是否组合会更好地为您服务。

标签: c++ arrays inheritance


【解决方案1】:

有多种选择。

  • 使用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]);
    };
    
  • 或者您也可以将std::vectorstd::array 与模板一起使用。

【讨论】:

  • 非常感谢,所以使用模板选项我必须单独分配每个组件,没有办法将减速延迟到子类。看来我最好还是使用向量或数组。
  • @wookie1:即使使用std::vector,除非您可以使用 C++11,否则您不能这样填充它。
  • 很好,你真的很有帮助。
【解决方案2】:

似乎最好在基类中使用私有纯虚方法并在派生类中实现。 目前尚不清楚你的“转换”数组是否总是有两个维度,这就是为什么我使用“你的类型”而不是应该存储在返回容器中的真实类型。大概是这样的:

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多