簡體   English   中英

C ++在頭文件中聲明函數原型的麻煩

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM