[英]Do I have to typedef on every Header file?
假設我有一個std::vector
的std::string
s。
// Foo.h
class Foo {
std::vector< std::string > mVectorOfFiles;
}
然后我使用typedef
使它成為StringVector
類型。
// Foo.h
typedef std::vector< std::string > StringVector;
class Foo {
StringVector mVectorOfFiles;
}
如果我有另一個采用StringVector
對象的類...
// Bar.h
class Bar {
Bar( const StringVector & pVectorOfFiles ); // I assume this produces a compile error (?) since Bar has no idea what a StringVector is
}
...我必須在Bar
的頭文件中再次使用typedef
嗎?
// Bar.h
typedef std::string< std::vector > StringVector;
class Bar {
Bar( StringVector pListOfFiles );
}
是否可以將typedef std::vector< std::string > StringVector
放在一個文件中,讓其他所有類都知道StringVector
類型?
#include "Foo.h"
所有文件都得到了typedef
。 所以,不,你沒有復制其在每一個文件(只要它包括Foo.h
,你可以放置typedef
在一個專用的文件是否適合您的需要。在你的情況,這將使意義並會一個改進,因為Bar.h
不應該依賴於Foo.h
具有typedef
和必要的包含這一事實。
我會保持簡單,並將其限制為一種類型,但要包含在使用該類型的所有文件中:
// StringVector.h
#ifndef STRINGVECTOR_H_
#define STRINGVECTOR_H_
#include <vector>
#include <string>
typedef std::vector< std::string > StringVector;
#endif
當然不是,你不必在所有頭文件中輸入typedef,只需在其余源文件包含的任何頭文件中執行。
改為創建一個類。
class Files {
};
然后你可以在任何需要的地方使用前瞻聲明;
class Files;
您將封裝適合文件的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.