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

2023-10-17C/C++开发问题
3

本文介绍了typedef 的类型作为成员函数的返回类型不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

This program fails to compile(using gcc-4.5). The error message says:

错误:‘myType_t’没有命名类型

error: ‘myType_t’ does not name a type

  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,有什么问题.

Now declaring typedef int myType_t; outside the class abc makes this compile. My confusion is, what is the problem if the return type of a member function is typedef'd inside the class.

推荐答案

来自 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()

这篇关于typedef 的类型作为成员函数的返回类型不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6