typedef vector size_type in header file

typedef vector size_type in header file

本文关键字:in header file type vector size typedef      更新时间:2023-10-16

我正在使用Visual Studio(不确定这是否相关(,我想在头文件中为vector<int>::size_type定义一个typedef。

这是我的标题:

#ifndef UTILS_H
#define UTILS_H
#include "pch.h"
#include <vector>
typedef int myint;
typedef vector<int>::size_type vi_sz;
#endif //UTILS_H

如果我尝试构建它,则会出现以下错误:

...utils.h(8): error C2143: syntax error: missing ';' before '<'
...utils.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
...utils.h(8): error C2039: 'size_type': is not a member of '`global namespace''

如果我typedef vector<int>::size_type vi_sz;移动到源文件,那么一切都很好。 请注意,我不需要用typedef int myint;执行此操作

有没有办法在标头中定义这种 typedef 以避免必须为每个源文件定义它,或者这在某种程度上是不好的做法?

如果我尝试构建它,则会出现以下错误:

请注意,这里:

#ifndef UTILS_H
#define UTILS_H
#include "pch.h"
#include <vector>
typedef int myint;
typedef vector<int>::size_type vi_sz;
#endif //UTILS_H

您没有using namespace std;(在头文件中尤其应该如此(,但是您编写vector<int>::size_type而不是std::vector<int>::size_type。因此,无法解析该名称。

如果我typedef vector<int>::size_type vi_sz;移动到源文件,那么 一切都很好

这会在.cpp文件中进行编译,因为您可能在typedef vector<int>::size_type vi_sz;文件之前有一个using namespace std;,因此解析了名称。简而言之,只需将其保留在头文件中,如下所示:typedef std::vector<int>::size_type vi_sz;

就像你缺少std命名空间一样。您可以执行以下操作。

  1. using namespace std;

  2. std::vector<int>::size_type

尝试任一,将解决您的问题。