c++ - typedef 的类型作为成员函数的返回类型不可见

标签 c++ scope typedef

此程序无法编译(使用 gcc-4.5)。错误消息说:

错误:“myType_t”没有命名类型

  1 class abc{
  2 //typedef int myType_t;
  3 
  4   public:
  5 typedef int myType_t;
  6 
  7     abc();
  8     myType_t fun1();
  9 };
 10 
 11 myType_t abc::fun1()
 12 {
 13   return 0;
 14 }
 15 
 16 int main()
 17 {
 18   abc abc1;
 19   return 0;
 20 }

现在在 abc 类之外声明 typedef int myType_t; 进行编译。 我的困惑是,如果成员函数的返回类型是类内部的 typedef,那么问题是什么。

最佳答案

来自 C++ 标准:

9.9 嵌套类型名称 [class.nested.type]

类型名称遵循与其他名称完全相同的范围规则。特别是,在类定义中定义的类型名称不能在没有限定的情况下在其类之外使用。

class X {
public :
   typedef int I;
   class Y { /  . . .  / };
   I a;
};

I b;            // error
Y c;            // error
X::Y d;         // OK
X::I e;         // OK

所以你需要访问它:

abc::myType_t abc::fun1()

关于c++ - typedef 的类型作为成员函数的返回类型不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6960778/

相关文章:

javascript - 重写javascript函数中的变量

java - 了解 web 应用程序中的 spring bean 作用域

java - Spring bean 销毁方法、单例和原型(prototype)范围

c++ - std::result_of 应用于 const 重载方法

C++:私有(private)方法返回的本地 typedef

c++ - Typedef 声明的形式为 `int typedef my_int;`

c++ - 两个物体的蛮力碰撞检测速度太慢

c++ - g++ 关闭基准测试的常量传播?

c++ - 如何检查是否在 Visual C++ 应用程序中的第三方 DLL 中创建了新线程

c++ - LNK2001 未解析的外部符号与 CPP_XLOPER