我使用static_cast时遇到问题。这是我的计划:
#include <iostream>
using namespace std;
class Mtx { // base matrix
private:
// refer to derived class
Mtx& ReferToDerived() {
return static_cast<Mtx&>(*this);
}
// entry() uses features of derived class
virtual double& entry(int i, int j){
return ReferToDerived() (i,j); // error appears here
}
protected:
int dimn; // dimension of matrix
public:
// define common functionality in base class that can
// be called on derived classes
double sum() { // sum all entries
double d = 0;
for (int i = 0; i < dimn; i++)
for (int j = 0; j < dimn; j++) d += entry(i,j);
return d;
}
};
class FullMtx: public Mtx {
double** mx;
public :
FullMtx(int n) {
dimn = n;
mx = new double* [dimn] ;
for (int i=0; i<dimn; i++) mx[i] = new double [dimn];
for (int i=0; i<dimn; i++)
for (int j=0; j<dimn; j++)
mx[i][j] = 0; // initialization
}
double& operator() (int i, int j) { return mx[i] [j]; }
};
class SymmetricMtx : public Mtx {
// store only lower triangular part to save memory
double** mx ;
public :
SymmetricMtx(int n) {
dimn = n;
mx = new double* [dimn];
for (int i=0; i<dimn; i++) mx[i] = new double [i+1];
for (int i=0; i<dimn; i++)
for (int j=0; j <= i; j++)
mx[i][j] = 0; // initialization
}
double& operator() (int i, int j) {
if (i >= j ) return mx[i][j] ;
else return mx[j][i]; // due to symmetry
}
};
int main()
{
FullMtx A(1000);
for (int i=0; i<1000; i++)
for (int j=0; j<1000; j++)
A(i,j)=1;
cout << "sum of full matrix A = " << A.sum() << '\n';
SymmetricMtx S(1000); // just assign lower triangular part
for (int i=0; i<1000; i++)
for (int j=0; j<1000; j++)
S(i,j)=1;
cout << "sum of symmetric matrix S = " << S.sum() << '\n';
}
当我运行它时,它说:不匹配调用'(Mtx)(int&amp;,int&amp;)' 我不明白什么是错的,我应该如何修改呢?它应该使用虚函数编写,但我不知道如何正确编写它。有人能帮我吗? 该程序应计算FullMatrix和SymmetricMatrix的所有元素的总和。
答案 0 :(得分:0)
在此处删除虚拟
virtual double& entry(int i, int j){
return (*this)() (i,j); // error appears here
}
在那里添加虚拟
class Mtx {
...
virtual double& operator() (int i, int j) = 0;
}
让派生类重载该运算符和voala。
class FullMtx: public Mtx {
...
virtual double& operator() (int i, int j) override { return mx[i] [j]; }
}
这也只是废话,正如已经指出的那样。你转换为相同的类型,而不是派生的类型。 除此之外,你不能转换为派生类型,因为在基础上你没有关于完全继承的信息 - 如果有人在你不知情的情况下从FullMtx派生出来怎么办?
Mtx& ReferToDerived() {
return static_cast<Mtx&>(*this);
}