C++给了我一个错误:对的调用没有匹配项

C++ gives me an error: no match for call to

本文关键字:调用 错误 一个 C++      更新时间:2023-10-16

我在使用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);
}