我必须在每个头文件上定义类型吗?

Do I have to typedef on every Header file?

本文关键字:定义 类型 文件      更新时间:2023-10-16

假设我有一个std::stringstd::vector

// 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
}

…我必须使用typedef再次在头文件的Bar ?

// 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和必要的include的事实。

我将保持它的简单,并限制为一种类型,包括在所有使用类型的文件:

// StringVector.h
#ifndef STRINGVECTOR_H_
#define STRINGVECTOR_H_
#include <vector>
#include <string>
typedef std::vector< std::string > StringVector;
#endif

当然不是,您不必在所有头文件中都定义类型,只需在其他源文件中包含的任何头文件中定义即可。

创建一个类。

class Files {
};

然后你可以在任何需要的地方使用前向声明;

class Files;

您将封装适合于文件的行为