Yai*_*adt 3 c++ inheritance virtual-functions matrix return-type
我正在寻找关于如何继续使用C++构建的类层次结构的建议.
基类是Matrix:
class Matrix
{
protected:
int rows;
int columns;
double* values;
public:
\\lots of stuff goes here. bla di bla di bla.
virtual Matrix operator+(const Matrix& addend) const;
\\etc.
}
Run Code Online (Sandbox Code Playgroud)
Squarematrix继承自Matrix
class Squarematrix : public Matrix
{
public:
Squarematrix operator+(const Squarematrix& addend) const;
}
Run Code Online (Sandbox Code Playgroud)
Operator +分别返回矩阵或squarematrix.由于operator +是一个虚函数,因此它不能编译,因为它必须在所有类中具有相同的返回类型.
那么我的选择是什么?
我可以使用普通函数而不是虚函数.这有点烦人,但在大多数情况下都不会引起问题.
在所有情况下我都可以返回一个矩阵.这基本上会使我的squarematrix类在***中使用正确的痛苦,因为我必须不断地从矩阵转向squarematrix.
我可以返回对squarematrix的引用.然后矩阵必须存储在堆上,并且无法确保将其安全删除.特别是如果我做这样的事情:
squarematrix a=b+(c+d);
Run Code Online (Sandbox Code Playgroud)
(c + d)将存储在堆上,并且没有指向它的指针,因此将被泄露.
有没有办法保持虚函数,但仍然有不同的返回类型?
在这种情况下你会提出什么建议?
谢谢你的帮助.期待您的回音.
我建议:
Squarematrix.Matrix构造方阵.Matrix来回答该查询.class Matrix
{
public:
Matrix(int r); // Construct a square matrix.
Matrix(int r, int c); // Construct a rectangular matrix.
bool isSquareMatrix() const { return (rows == columns); }
Matrix operator+(const Matrix& addend) const;
private:
int rows;
int columns;
double* values;
}
Run Code Online (Sandbox Code Playgroud)