c++ - 看到 std::vector<Typo> 和 std::vector<struct Typo> 时发出的编译器诊断之间存在差异的原因是什么

标签 c++ compiler-errors

考虑这两个程序及其尝试编译。

#include <vector>

int main() {
    std::vector<struct Typo> a; // Errors centered around `Typo` being an incomplete type
}
例如,

gcc 6.3 给出了以 Typo 为不完整类型为中心的错误消息,包括

/usr/include/c++/6/bits/stl_vector.h:161:9: error: invalid use of incomplete type ‘struct main()::Typo

#include <vector>

int main() {
    std::vector<Typo> b; // Errors centred around `Typo` not being defined
}
例如,

gcc 6.3 给出了以 Typo 未定义为中心的错误,包括

prog.cpp:4:14: error: ‘Typo’ was not declared in this scope

当然,两个 vector 实例都是错误的,但程序注释中引用的不同诊断消息的基本原理是什么?

最佳答案

struct Typo是一个详细的类型说明符。这会影响名称查找的工作方式。

[basic.lookup.elab]

2: If the elaborated-type-specifier has no nested-name-specifier, and unless the elaborated-type-specifier appears in a declaration with the following form:

class-key attribute-specifier-seq identifier ;

the identifier is looked up according to [basic.lookup.unqual] but ignoring any non-type names that have been declared. If the elaborated-type-specifier is introduced by the enum keyword and this lookup does not find a previously declared type-name, the elaborated-type-specifier is ill-formed. If the elaborated-type-specifier is introduced by the class-key and this lookup does not find a previously declared type-name, or if the elaborated-type-specifier appears in a declaration with the form:

class-key attribute-specifier-seq identifier ;

the elaborated-type-specifier is a declaration that introduces the class-name as described in [basic.scope.pdecl].

所以在 std::vector<struct Typo> a; , 因为 struct Typo未找到先前声明的 Typo ,它作为类型的前向声明。因此,可能1提示它得到的类型不完整的 vector 实例化,因为它会尝试用它做一些事情。

std::vector<Typo> b; 期间, 查找 Typo一无所获。它没有先前的声明,因此此时应该发出一个诊断,表明此标识符未声明。


<子> 1 - 取决于您正在编译的标准,以及您使用的 vector 的哪些成员。添加了对不完整类型的支持。

关于c++ - 看到 std::vector<Typo> 和 std::vector<struct Typo> 时发出的编译器诊断之间存在差异的原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460967/

相关文章:

c - 错误: Expected expression before 'DATA/* : typedef struct DATA DATA */

c++ - 如何使用 FirstCHildElement 从 xml 标签获取值

c++ - Boost.Asio 的可扩展性

c++ - 如何防止我的应用程序窗口转到另一台显示器(Electron + macOS)

c++ - 1 最终编译器错误 :( can someone explain in real simple for me

Angular2/TypeScript - 访问类数组类型的对象元素

c++ - 在 C++ 中绘制(基元、线条等)的最佳通用跨平台解决方案?

从子到父导航的 C++ 聚合

python - mysql-python的pip安装错误无法正常工作

java - 简单的Java代码无法编译- “Create class '中的 'java.lang'对象'”