在基类和派生类上操作时如何返回派生类型
How to return derived type while operating over base and derived class?
我有两个类,my_matrix
和my_vector
类,其中my_vector
来自my_matrix
。
当我做my_matrix tmp = vec * mat
时,它返回一个矩阵(mat
是my_matrix
的实例,vec
是my_vector
的实例)。我在这里很好。
但是当我做my_vector tmp = mat * vec
时,我在clang++中得到这个错误:
无法从'
my_matrix
'转换为'my_vector
'
和g++中的错误:
我想我知道问题出在哪里了。请求从'
my_matrix
'转换为'my_vector
'非标量类型
mat
和vec
相乘后,返回类型为my_matrix
, 不能将基类强制转换为派生类。
你认为这个问题的解决方案是什么?
我已经尝试定义void operator*(my_vector&, my_matrix&)
(不是派生类的成员函数),它在派生类中调用my_vector operator*(my_matrix&)
,但到目前为止它不起作用。
class my_matrix{
public:
my_matrix operator*(my_matrix& other_mat){
my_matrix tmp(row, other_mat.col);
// for loop to matrix multiply that fill up the tmp
return tmp;
}
};
class my_vector:public my_matrix{
public:
// not sure if I need operator* here
// Somehow I want to bring the my_vector tmp = mat * vec; here so
// it would return vector instead of matrix
// I have tried : but not successful
// my_vector operator*(my_matrix&)
// void operator*(my_vector&, my_matrix&); (non member)
};
int main(){
my_matrix mat = {{1,2,3},{4,5,6}}; // 2x3
my_vector vec = {1,2,3}; // 3x1
my_vector tmp = mat * vec; // 2x3 * 3*1 gives 2x1 vector
}
试试这样:
class my_matrix {
public:
my_matrix operator*(const my_matrix& other_mat) const {
my_matrix tmp(row, other_mat.col);
// for loop to matrix multiply that fill up the tmp
return tmp;
}
};
class my_vector : public my_matrix {
public:
using my_matrix::operator*;
my_vector operator*(const my_vector& other_vec) const {
my_vector tmp(...);
// for loop to vector multiply that fill up the tmp
return tmp;
}
};
my_vector operator*(const my_matrix &lhs, const my_vector &rhs)
{
my_vector tmp(...);
// for loop to vector multiply that fill up the tmp
return tmp;
}
int main() {
my_matrix mat = {{1,2,3},{4,5,6}}; // 2x3
my_vector vec = {1,2,3}; // 3x1
my_vector tmp = mat * vec; // 2x3 * 3x1 gives 2x1 vector
}
首先,现有的operator*
的参数是错误的:
my_matrix operator*(my_matrix& other_mat){
*
操作符的形参应该是const
,方法应该是const
本身。毕竟,乘法运算符不应该修改任何一个操作数:
my_matrix operator*(const my_matrix& other_mat) const {
解决了这个问题后,现在可以有意义地重载操作符:
my_vector operator*(const my_vector& other_mat) const {
并以任何你想定义的方式实现乘法运算。
现在,乘以my_matrix
返回my_matrix
,乘以my_vector
返回my_vector
。您的my_matrix
重载*
运算符,并且返回值取决于您将其乘以什么。
相关文章:
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 返回派生类型时出现协变类型错误
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- C++ 基类调用但返回派生类
- dynamic_cast派生类返回 nullptr
- 自定义派生的 std::exception 类的 'what' 函数返回神秘的废话
- 是否可以从派生类返回基类的实例?
- typeid.name 返回派生类类型之前的数字
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- 无法返回派生类型的标准::unique_ptr<>
- 派生类继承的 getter,找不到返回正确值的方法
- 视觉C++ dynamic_cast返回 NULL,尽管对象是派生类型
- 从基类方法返回对派生类的引用
- 如何在不转换回基类类型的情况下返回派生类型的对象?
- 从虚拟方法返回派生对象作为基础
- 不能返回派生的类(无法转换)
- 多态性是否适用于值?或者在按(基)值返回时使用派生类的移动构造函数
- C++ shared_ptr从派生方法返回此值
- 在基类和派生类之间正确设置函数的返回
- 从多个派生类返回函数