【问题标题】:error xxx in yyy does not name a typeyyy 中的错误 xxx 未命名类型
【发布时间】:2016-12-04 14:50:34
【问题描述】:

编译文件error_xxx_does_not_name_a_type.cpp,为什么会报错
error_xxx_does_not_name_a_type.cpp:5:28: error: ‘A’ in ‘struct std::pair<bool, int>’ does not name a type std::pair<bool, int> ::A::B::C::D::get_i()

// error_xxx_does_not_name_a_type.h
#pragma once
#include <utility>

namespace A{ namespace B{ namespace C{
struct D
{   
    std::pair<bool, int> get_i();
    std::pair<bool, int> get_j();
    std::pair<bool, int> get_k();
    int get_l();
};  
}}}

// error_xxx_does_not_name_a_type.cpp
#include "error_xxx_does_not_name_a_type.h"

#if 1 // gives me the error
std::pair<bool, int> ::A::B::C::D::get_i()
{ return {true, 10}; }
#endif
// But none of the below do
// missing ::
std::pair<bool, int> A::B::C::D::get_j()
{ return {true, 10}; }
// trailing return type
auto ::A::B::C::D::get_k()->
    std::pair<bool, int>
{ return {true, 10}; }
// return type int
int ::A::B::C::D::get_l()
{ return 10; }

我用g++ -Wall -Wextra -std=c++14 -c error_xxx_does_not_name_a_type.cppg++ (Ubuntu 5.3.0-3ubuntu1~14.04) 5.3.0 20151204 编译过

【问题讨论】:

  • 很惊讶没有一个高票的骗子。

标签: c++ c++11 compiler-errors g++ c++14


【解决方案1】:

因为(空格)在此上下文中无关紧要,而:: 用作范围解析运算符,应用于std::pair&lt;bool, int&gt;

对于编译器,

std::pair<bool, int>::A...

一样
std::pair<bool, int>:: A...

和一样

std::pair<bool, int> ::A...

一样
std::pair<bool, int> :: A...

因此,编译器正在std::pair&lt;bool, int&gt; 范围内寻找A,这显然会失败。

见:Space(s) before/after the scope resolution operator

【讨论】:

  • 解释但没有解决办法
  • @LightnessRacesinOrbit:是的,那又怎样?问题是:“为什么我会出错......”。无论如何,问题中都提供了解决方法。
【解决方案2】:

Here 是一个更简洁的复制示例:

struct T{};
T A();
T ::A() { return T(); }

// error: no 'int T::A()' member function declared in class 'T'

(注意 GCC 尝试将 auto-int 返回类型作为 C 的保留!)

这是一个 C++ 怪癖。您混淆了解析器,因为看起来您正在尝试使用std::pair&lt;bool, int&gt; ::A::B::C::D 做某事,而这显然不存在。 (这里忽略了间距,尽管我们通常是这样写的。)

省略::。有了函数定义,你就永远不需要它了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多