C++给了我一个错误:对的调用没有匹配项
C++ gives me an error: no match for call to
我在使用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&,int&"的调用我不明白哪里出了问题,我应该如何修改它?它应该使用虚拟函数编写,但我不知道如何才能正确编写。有人能帮我吗?这个程序应该计算FullMatrix和SymmetricMatrix的所有元素的总和。
删除此处的虚拟
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]; }
}
正如已经指出的那样,这也是无稽之谈。您转换为同一类型,而不是派生类型。此外,你不能强制转换为派生类型,因为在base中你没有关于完全继承的信息——如果有人在你不知情的情况下从FullMtx派生呢?
Mtx& ReferToDerived() {
return static_cast<Mtx&>(*this);
}
相关文章:
- C++模板类 - 继承调用错误的函数
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 std::find 时没有匹配的函数调用错误
- 使用成员初始值设定项列表时没有匹配的函数调用错误
- C++调用错误签名的函数
- C++ 类成员调用错误 C3861
- C bool表达式作为函数参数调用错误的超载
- C ++尝试访问映射中的元素会给我一个不匹配的函数调用错误
- 当提供巨大的输入时,中止在堆栈操作程序中调用错误
- C++类静态成员函数调用错误
- 如何调查随机安卓原生函数调用错误?
- 引发实例后终止调用 - C++错误
- 如何修复传递参数时调用错误函数的主函数?(C++)
- 没有用于调用错误的匹配函数.将字符串推送到向量中
- 从括号内的initializer_list构造时,将调用错误的过载
- 为什么初始值设定项列表中的元素数会导致不明确的调用错误
- VC 15调用错误的复制构造函数以捕获lambda
- 在 C++ 中没有针对调用错误的匹配函数
- C++:函数调用错误:标识符"name"未定义,如果已定义?
- 为什么 GCC 在显式指定模板参数时会产生奇怪的错误并尝试调用错误的方法?