簡體   English   中英

來自基類的c ++構造函數

[英]c++ constructor from base class

是為了獲取基類對象的派生類實現構造函數,它是回到實踐還是其他一些邪惡的軟件設計? 我需要它在以下Vector / Matrix Framework中。 我想只在Matrix類(在operator *中)定義Matrix / Vector乘法的代碼一次。 但是在Matrix類中我只能返回抽象基類類型:

// Base
template<class Value_T, unsigned int N>
class VectorT
{
    ...
};

// Derived
class Vector4 : public VectorT<double, 4>
{
public:
    ...
    Vector4(const VectorT<double, 4>& base);    // base class constructor   
    ...
};

// multiplication operator in a matrix class using the abstract VectorT base type
VectorT<value_type, N> operator*(const VectorT<value_type, N>& v) const
{
    VectorT<value_type, N> vRes;
    ...
    return vRes;    // return by value
}

// usage
Vector4 v;
Matrix4 m;

VectorT<double, 4> vMult = m * v;   // this works but is not what I want

Vector4 vMult = m * v;              // this is what I want, but only works with the base class constructor of Vector4

我的主要目標是重用Matrix / Vector乘法代碼,並在矩陣類中為Matrix-和Vector類的所有可能模板規范定義它。

正如TC在評論中指出的那樣,您甚至不需要讓派生類使用Vector4類型。

這是一個3x3乘3的例子:

#include <iostream>

template<class Value_T, unsigned int N>
struct VectorT
{
  VectorT() : data() { }
  Value_T data[N];
};

typedef VectorT<double, 3> Vector_d3;

template < class Value_T, unsigned int N, unsigned int M >
struct MatrixT : VectorT<VectorT<Value_T, M>, N>
{
  VectorT<Value_T, N> operator* (VectorT<Value_T, M> const & v)
  {
    VectorT<Value_T, N> result;
    for (size_t i(0); i < M; ++i)
    {
      for (size_t j(0); j < N; ++j) result.data[i] += data[i].data[j] * v.data[j];
    }
    return result;
  }
};

typedef MatrixT<double, 3, 3> Matrix_d33;

int main()
{
  /*
    m =
    1 2 3 
    4 5 6
    7 8 9
  */
  Matrix_d33 m;
  m.data[0].data[0] = 1;
  m.data[0].data[1] = 2;
  m.data[0].data[2] = 3;
  m.data[1].data[0] = 4;
  m.data[1].data[1] = 5;
  m.data[1].data[2] = 6;
  m.data[2].data[0] = 7;
  m.data[2].data[1] = 8;
  m.data[2].data[2] = 9;
  /*
    v =
    5 4 3
  */
  Vector_d3 v;
  v.data[0] = 5;
  v.data[1] = 4;
  v.data[2] = 3;
  /*
  res =
  1*5 + 2*4 + 3*3 = 22
  4*5 + 5*4 + 6*3 = 58
  7*5 + 8*4 + 9*3 = 94
  */
  Vector_d3 res = m*v;

  std::cout << res.data[0] << std::endl;
  std::cout << res.data[1] << std::endl;
  std::cout << res.data[2] << std::endl;

}

代碼打印:

22
58 
94

在派生類對象的構造函數中使用基類對象是一種非常有效的方法。 可以將其視為基類部分的復制構造函數和派生類部分的默認構造函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM