在基类和派生类上操作时如何返回派生类型

How to return derived type while operating over base and derived class?

本文关键字:派生 何返回 返回 类型 基类 操作      更新时间:2023-10-16

我有两个类,my_matrixmy_vector类,其中my_vector来自my_matrix

当我做my_matrix tmp = vec * mat时,它返回一个矩阵(matmy_matrix的实例,vecmy_vector的实例)。我在这里很好。

但是当我做my_vector tmp = mat * vec时,我在clang++中得到这个错误:

无法从' my_matrix '转换为' my_vector '

和g++中的错误:

请求从' my_matrix '转换为' my_vector '非标量类型

我想我知道问题出在哪里了。matvec相乘后,返回类型为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重载*运算符,并且返回值取决于您将其乘以什么。