为什么我的静态方法的返回值与定义的构造函数(在 c++ 中)之间存在类型不匹配?

Why there is a type mismatch between my static method's return value and the defined constructor (in c++)?

本文关键字:之间 存在 类型 不匹配 c++ 返回值 静态方法 我的 定义 为什么 构造函数      更新时间:2023-10-16

我有一个Matrix类,我想在其中定义一个静态方法来乘以两个矩阵。

当我试图编译这个C++代码时,我得到了一个错误,上面写着"没有用于初始化‘Matrix’的匹配构造函数"!

这是我的构造函数签名:

Matrix(Matrix& A);

这是我的乘法方法:

static Matrix mult(Matrix &A,Matrix &B){
    if (A.n != B.m)
        throw 2;
    Matrix C(A.m,B.n);
    for (int i=0;i<A.m;i++){
        for (int j=0;j<B.n;j++){
            for (int k=0;k<A.n;k++)
                C.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j];
        }
    }
    return C;
}

这是触发mult函数并填充z变量的代码:

Matrix z = Matrix::mult(x,y);

怎么了?!为什么我的构造函数与返回值不匹配?!

这是我的整个矩阵类:

class Matrix{
public:
    int m,n;
    bool** matrix;
    Matrix(int m,int n);
    Matrix(Matrix& A);
    int get_m();
    int get_n();
    void set(int,int,bool);
    bool get(int,int);

    Matrix& add(Matrix&);
    Matrix& operator=(Matrix&);
    friend ostream& operator << (ostream& ,Matrix&);
    string toString();
    ~Matrix();
    static Matrix mult(Matrix &A, Matrix &B);

};

为什么我的构造函数与返回值不匹配?!

因为您按值返回本地对象,并且您为Matrix提供的唯一副本构造函数采用非const引用。这行不通。

您可以通过提供一个采用const引用的复制构造函数来修复此问题:

Matrix(const Matrix& A);

考虑以下相同情况的说明:

#include "main.h"
class Foo
{
public:
    Foo (int n) : mN (n) {}
    Foo (Foo& rhs) : mN (rhs.mN) {}
    int DaNum() const { return mN * 2; }
private:
    int mN;
};
Foo Gimme(int n)
{
    Foo ret(n);
    return ret;
}
int main()
{
  Foo foo = Gimme (42);
  cout << foo.DaNum();
}

按原样,这无法使用进行编译

main.cpp:21:22: error: no matching function for call to ‘Foo::Foo(Foo)’

但进一步阅读,我们可以看到编译器继续详细说明:

main.cpp:21:22: error: no matching function for call to ‘Foo::Foo(Foo)’
main.cpp:21:22: note: candidates are:
main.cpp:7:5: note: Foo::Foo(Foo&)
main.cpp:7:5: note:   no known conversion for argument 1 from ‘Foo’ to ‘Foo&’
main.cpp:6:5: note: Foo::Foo(int)
main.cpp:6:5: note:   no known conversion for argument 1 from ‘Foo’ to ‘int’
ninja: build stopped: subcommand failed.

更改:

Foo (Foo& rhs) : mN (rhs.mN) {}

至:

Foo (const Foo& rhs) : mN (rhs.mN) {}

解决问题。