具有非默认构造函数的多重继承的内存分配

Memory allocation for multiple inheritance with non-default constructors

我有点难以理解多重继承。显然我选择解决一个非常复杂的问题,它具有多重继承和菱形问题。即使我发现了几个与我的问题相似的案例,例如 this one,我的问题是关于内存而不是执行顺序。

假设我有以下内容:

class Matrix {
public:
  Matrix(int rows, int Cols) {
    // Build matrix of zeros
  }
};

class Symmetric : public virtual Matrix {
public:
  // It's enough to call Matrix constructor using the same number of rows and cols
  Symmetric(int size) : Matrix(size, size) {}
};

class PosDef : public virtual Matrix {
public:
  // We need different constructor, matrix of zeros is not pos def
  PosDef(int size) {
    // Build matrix of ones
  }
};

class SymmPosDef : public Symmetric, public PosDef {
public:
  // We basically want to use the PosDef constructor that gives symmetric matrix
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};

因为我已经为非默认构造函数提供了初始化 SymmPosDef 对象的唯一方法是使用复杂的链 SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {} 而我的问题是我要构建多少个矩阵?

我是为 Matrix 分配一次 space,为 Symmetric 分配一次(这将是相同的零元素),一次为 PosDef 分配,还是我重复使用相同 space?

因为矩阵的大小可能很大,所以我想做尽可能少的工作。

Matrix 在最派生的 class 中仅初始化一次(从初始化列表)。 但是所有构造函数 body 都会被调用。

有:

class SymmPosDef : public Symmetric, public PosDef {
public:
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};

你会:

  • Matrix(size, size)
  • (Symmetric(int size) : Matrix(size, size) 跳过)
  • Symmetric(int size) 正文 (/*Empty*/).
  • (PosDef(int size) : Matrix(size, size) 已跳过)
  • PosDef(int size) 正文 ( /* Build matrix of ones */ )
  • SymmPosDef(int size) 正文 (/*Empty*/).