如何解决矩阵的编写接口
我正在用 C++ 为 Matrix 类编写一个接口
所以所有的函数都需要是虚拟的
现在在下面的代码中,我定义了一个虚函数 virtual Matrix add(Matrix A,Matrix B) const = 0;
我看到的问题是类 Matrix 未定义。所以我很困惑我应该定义
接口中的类矩阵 ?或者有更好的方法来实现接口
class MatrixInterface
{
public:
virtual Matrix add(Matrix A,Matrix B) const = 0;
};
出现编译错误的更新代码:
在 Matrix.cpp 添加方法:member function declared with 'override' does not override a base class memberC/C++(1455)
#include <iostream>
#include "MatrixInterface.h"
class Matrix : public MatrixInterface
{
public:
Matrix *add(MatrixInterface *A,MatrixInterface *B) override{
// implementation
};
};
class MatrixInterface
{
public:
virtual MatrixInterface *add(MatrixInterface *A,MatrixInterface *B) const = 0;
};
解决方法
从接口类中的 add
方法返回接口类型,然后在子类中,您可以覆盖虚方法并将返回类型更改为 Matrix
(或任何 narrower type ).
class MatrixInterface
{
public:
virtual MatrixInterface* add(MatrixInterface* A,MatrixInterface* B) const = 0;
};
派生类:
class Matrix : public MatrixInterface
{
public:
Matrix* add(MatrixInterface* A,MatrixInterface* B) override { // implementation };
};
您需要使用指针来利用 covariant return types。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。