基类的c ++构造函数 [英] c++ constructor from base class

查看:72
本文介绍了基类的c ++构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为派生类实现构造函数以获取基类对象,是回溯实践还是其他邪恶的软件设计?我在下面的Vector/Matrix框架中需要它.我只想为Matrix/Vector乘法定义代码-在Matrix类中(在operator *中).但是在Matrix类中,我只能返回抽象基类类型:

Is it back practice or some other kind of evil software design to implement a constructor for a derived class getting a base class object? I am needing it in the following Vector/Matrix Framework. I want to define the code for the Matrix/Vector multiplication only once - in the Matrix class (in operator*). But within the Matrix class I can only return the abstract base class type:

// 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类中为Matrix-和Vector类的所有可能的模板规范定义它.

My main goal is to reuse the code of Matrix/Vector multiplication and therefor define it in the matrix class for all possible template specifications of the Matrix- and Vector classes.

推荐答案

在派生类对象的构造函数中使用基类对象是一种完全有效的方法.可以将其视为基类部分的复制构造函数和派生类部分的默认构造函数.

Using a base class object in the constructor of a derived class object is a perfectly valid approach. Think of that as Copy constructor for base class portion and default constructor for derived class portion.

这篇关于基类的c ++构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆