从c ++中的函数返回继承类的最佳方法

时间:2017-02-22 21:40:34

标签: c++ inheritance matrix return-type virtual-functions

我正在寻找有关如何继续使用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.
}

Squarematrix继承自Matrix

class Squarematrix : public Matrix
{
public:

    Squarematrix operator+(const Squarematrix& addend) const;

}

Operator +分别返回矩阵或squarematrix。因为operator +是一个虚函数,所以不会编译,因为它必须在所有类中都有相同的返回类型。

那么我的选择是什么?

我可以使用普通函数而不是虚函数。这有点烦人,但在大多数情况下都不会引起问题。

我可以在所有情况下返回矩阵。这基本上会使我的squarematrix类在***中使用正确的痛苦,因为我必须不断地从矩阵转向squarematrix。

我可以返回对squarematrix的引用。然后矩阵必须存储在堆上,并且无法确保将其安全删除。特别是如果我做这样的事情:

squarematrix a=b+(c+d);

(c + d)将存储在堆上,并且没有指针,因此会泄露。

有没有办法保留虚函数并且仍然有不同的返回类型?

在这种情况下你会提出什么建议?

感谢您的帮助。期待收到你的回复。

2 个答案:

答案 0 :(得分:6)

我建议:

  1. 删除Squarematrix
  2. Matrix添加构造函数以构造方阵。
  3. 如果矩阵是否为方形矩阵的知识对您的应用程序有帮助,请在Matrix中添加成员函数来回答该查询。
  4. 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;
    
    }
    

答案 1 :(得分:1)

这称为返回类型协方差(https://en.wikipedia.org/wiki/Covariant_return_type)。

旧的编译器不支持它,但现在很多人都支持它。例如,我的代码在Visual Studio 2017中编译得很好。这是一篇关于它在c ++中的使用和限制的文章:https://aycchen.wordpress.com/2009/08/17/covariant-return-type-in-cpp/

C#尚不支持,但正在考虑将来的版本。请参阅https://github.com/dotnet/csharplang/issues/49

新版本的Java也支持它。请参阅https://blogs.oracle.com/sundararajan/covariant-return-types-in-java

除了实现问题之外,据我所知,没有理由不将它添加到多态语言中。我不相信它会导致错误,尽管由于Java中的不完美实现会导致错误 - 请参阅https://dzone.com/articles/covariant-return-type-abyssal

相关问题