[英]C++ Trouble declaring function prototype within header file
我已经获得以下代码在MatrixTest.cpp函数中使用:
Matrix matrix = Matrix::Zeros(2,4)
目的是“用静态零创建一个2x4零的矩阵”,我需要能够在头文件“Matrix.h”中添加一些东西,它允许“MatrixTest.cpp”编译上面的代码行。 到目前为止,这是我的头文件中的代码:
#ifndef MATRIX_H_
#define MATRIX_H_
class Matrix {
protected:
// These are the only member variables allowed!
int noOfRows;
int noOfColumns;
double *data;
int GetIndex (const int rowIdx, const int columnIdx) const;
public:
Matrix (const int noOfRows, const int noOfCols);
Matrix (const Matrix& input);
Matrix& operator= (const Matrix& rhs);
~Matrix ();
Matrix Zeros(const int noOfRows, const int noOfCols);
};
#endif /* MATRIX_H_ */
这给出了我的.cpp文件中的错误,我无法在没有对象的情况下调用成员函数Matrix Matrix :: Zeros(int,int)。 但是肯定Zeros是我的对象而我的Matrix类是我的类型?
如果我将头文件中的代码更改为以下内容:
static Zeros(const int noOfRows, const int noOfCols);
然后我在我的.h文件中得到一个错误,说“禁止声明'Zeros'没有类型和我的.cpp文件中的错误说”从'int'转换为非标量类型'Matrix'请求“
我很困惑,因为我认为我的类型是Matrix,因为它出现在Matrix类下面,并且因为Matrix :: Zeros(2,4)遵循构造函数Matrix(const int noOfRows,const int noOfCols)然后就不会不是从'int'到非标量类型的转换问题。
任何人都可以帮忙解决这个问题,因为我似乎在这些错误之间来回走动?
函数的签名应该是
static Matrix Zeros(const int noOfRows, const int noOfCols);
static
关键字不是返回类型, Matrix
是。 相反, static
关键字表明您不需要Matrix
的实例来调用该方法,而是可以将其称为
Matrix matrix = Matrix::Zeros(2,4)
需要明确的是,如果你没有使用这个词static
,那么你就必须做一些像
Matrix a{};
Matrix matrix = a.Zeros(2,4);
但可以看到的是, Zeros
方法不依赖于国家a
所以它会是有意义的方法是static
,而不是。
由于static
不是返回类型,并且您的函数返回Matrix
,这将是您的返回类型。
将函数签名更改为static Matrix Zeros(const int noOfRows, const int noOfCols);
应该做的伎俩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.