基类的c ++构造函数

编程入门 行业动态 更新时间:2024-10-22 07:49:22
本文介绍了基类的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 ++构造函数

本文发布于:2023-10-31 07:33:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545446.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!