Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;在头文件中声明函数原型时出现问题_C++_Class_Header Files - Fatal编程技术网

C++ C++;在头文件中声明函数原型时出现问题

C++ C++;在头文件中声明函数原型时出现问题,c++,class,header-files,C++,Class,Header Files,在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 onl

在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::Zeros(int,int)。但肯定零是我的目标,我的矩阵类是我的类型

如果我将头文件中的代码更改为以下内容:

static Zeros(const int noOfRows, const int noOfCols);
然后我在.h文件中得到一个错误,说“禁止在没有类型的情况下声明'zero',在.cpp文件中得到一个错误,说“请求从'int'转换为非标量类型'Matrix'”

我很困惑,因为我会认为我的类型是Matrix,因为它出现在类矩阵下面,而且Matrix::Zeros(2,4)遵循构造函数矩阵(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
的状态,因此将该方法改为
静态
是有意义的。

因为
静态
在这里不是返回类型,而您的函数返回的是
矩阵,这将是您的返回类型

将函数签名更改为
静态矩阵零(const int noOfRows,const int noOfCols)
应该能做到。

他接受你的答案显然表明我读得太多了well@R_Kapp不用担心:)安全总比抱歉好,尤其是在编程中,尽可能的具体和准确是值得的。是的,谢谢!对静态的解释帮助了我的理解它可能是静态或矩阵的一种选择,但它同时使用了这两种方法