为什么我的静态方法的返回值与定义的构造函数(在 c++ 中)之间存在类型不匹配?
Why there is a type mismatch between my static method's return value and the defined constructor (in c++)?
我有一个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) {}
解决问题。
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 为什么C++容器之间存在比较运算符
- 为什么返回前的值和返回后的值之间存在差异?
- 为什么堆栈中的函数局部变量之间存在内存空间
- 相对于一元算术运算符+,C和C++之间存在差异的原因是什么
- 函数返回类型和名称之间存在未知关键字
- 我找不到程序中的歧义,但编译器说 check(int) 和 check(float) 之间存在歧义
- 引用的初始化无效:指针和值之间存在差异
- VS2005调试模式和发布模式之间存在巨大的性能影响
- 为什么在Mac OS X上使用size_t时uint32_t和uint64_t之间存在歧义
- 如何提取两个括号之间存在的字符串
- 来自 vtable 的未定义符号是否意味着接口和实现之间存在错误
- 实时时间和用户时间之间存在巨大差异
- 在程序继续执行的同时,如何使代码的两部分之间存在时间间隔或延迟?C++
- g++输出和Visual Studio输出之间存在差异.浮点变量
- 为什么我的静态方法的返回值与定义的构造函数(在 c++ 中)之间存在类型不匹配?
- 复制构造函数和转发构造函数之间存在冲突
- libc++和libstdc++之间存在差异
- 指针上的interpret_cast在char和unsigned char之间存在缺陷
- 为什么在多重定义的情况下char*和char[]之间存在差异