我必须在每个头文件上定义类型吗?
Do I have to typedef on every Header file?
假设我有一个std::string
的std::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;
您将封装适合于文件的行为
相关文章:
- 使用QJsEngine在Qt中注册自定义类型
- 在UE4中使用未定义类型'UTextBlock'
- 修改"std::set"中用户定义类型的值
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 如何使自定义类型在unordered_map中用作键
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- Qt5 远程对象 + 自定义类型,但不在 POD 中
- 为什么转换函数声明不需要至少一个定义类型说明符
- 标准::原子中的自定义类型
- 如何使用自定义类型声明Arduino数组?
- 如何在 Cython 中定义返回 cpp 定义类型的函数?
- 使用自定义访问者时具有自定义类型的提升变体失败(源自 boost::static_visitor)
- 您可以将binary_search应用于具有自定义类型的矢量吗?
- 在自定义类型图中重用 SWIG 映射
- 扩展自定义类型的spdlog
- vim使用户定义类型的COLOR与C++中的基本类型相同
- 重载自定义类型的 std::to_string 和 std::to_chars?
- 具有未声明/未定义类型的 typedef 结构
- 函数重载:内置类型与用户定义类型