[英]C++: “error C4430: missing type specifier - int assumed” For constructor and invalid declaration for destructor
[英]“missing type specifier” error on constructor declaration
我在2個不同的文件中有2個類:
RegMatrix.h:
#ifndef _RM_H
#define _RM_H
#include "SparseMatrix.h"
...
class RegMatrix{
...
RegMatrix(const SparseMatrix &s){...} //ctor
...
};
#endif
SparseMatrix.h:
#ifndef _SM_H
#define _SM_H
#include "RegMatrix.h"
...
class SparseMatrix{
...
SparseMatrix(const RegMatrix &r){...} //ctor
...
};
#endif
在構造函數行上我得到錯誤:
錯誤C4430:缺少類型說明符 - 假定為int。
錯誤C2143:語法錯誤:'&'之前缺少','
但是當我添加類聲明時
class SparseMatrix;
在RegMatrix.h文件中
class RegMatrix;
在SparseMatrix.h文件中它工作正常。 我的問題是,如果我有包含,為什么需要它? 10X。
你不能有循環#includes(一個文件#includes另一個#includes第一個文件)。 前面聲明其中一個類而不是#include會打破鏈並允許它工作。 聲明類名允許您使用該名稱,而無需了解該類的內部位。
順便說一下,對圓形#includes的渴望是一種設計氣味。 也許你可以創建一個兩個類可以依賴的接口? 然后他們就不必相互依賴。
你的標題包含不起作用,看看如果我在解析后包括SparseMatrix.h會發生什么:
#ifndef _SM_H
#define _SM_H
/// start of #include "RegMatrix.h"
#ifndef _RM_H
#define _RM_H
/// start of #include "SparseMatrix.h" inside "RegMatrix.h"
#ifndef _SM_H
// skipping, because _SM_H is defined and the condition is false
#endif
/// end of #include "SparseMatrix.h" inside "RegMatrix.h"
class RegMatrix{
...
RegMatrix(const SparseMatrix &s){...} //ctor
...
};
#endif
/// end of #include "RegMatrix.h"
...
class SparseMatrix{
...
SparseMatrix(const RegMatrix &r){...} //ctor
...
};
#endif
所以基本上,SparseMatrix是未定義的。 你無能為力。 只需申報你的班級前瞻聲明。
如果首先包含RegMatrix.h
,它將包含SparseMatrix.h
。 然后,這將返回包括RegMatrix.h
,並跳過,因為已定義標頭防護。 然后, SparseMatrix
繼續進行定義,除了RegMatrix
從未甚至宣稱。 然后你得到一個錯誤。
你不能有圓形包含。 你必須轉發聲明其中一個或兩個,就像你做的那樣。
聲明如
class SparseMatrix;
被稱為前瞻性聲明。 它告訴編譯器“某處”有一個該名稱的類。 只要前向聲明文件使用指針或對前向引用類的引用,它就會使編譯器滿意並且工作正常。 這是因為,從編譯器的角度來看,指針或引用只是4個字節,與類內容無關。
在OP的代碼中, SparseMatrix
和RegMatrix
都只用作(const)引用,因此前向聲明足以使其工作。
但是,如果前向聲明文件執行某些操作,需要編譯器知道其大小,例如
void foo( SparseMatrix ); // note pass by value
然后編譯器會抱怨:-)
在OP提出的特殊情況下,我傾向於完全拋棄共同的#include
並僅基於前向聲明來設計界面。 實現(即.cpp文件) 可能必須包含兩個頭文件,但這不是問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.