typedef映射作为返回类型到函数会引发编译器错误

Typedef map as return type to a function throws a compiler error

本文关键字:编译器 错误 函数 映射 返回类型 typedef      更新时间:2023-10-16

typedef a map并使用 typedef名称作为函数的返回参数失败。

以下是一个伪代码,解释了场景:

/**
* a.h
*/
class A 
{
   public:
       typedef std::map<string,int> Int_map;
       A();
       ~A();
       const Int_map& getMap(); 
   private:
     Int_map my_map;
}

/**
* a.cpp
*/
 A::A() {}
 A::~A() {}

 const Int_map& A::getMap() // gives a compiler error : Int_map does not name a type
{
   return my_map;
}

但是,如果我在" A.CPP"中使用以下声明,则没有编译器错误。(注意:A.H文件仍然包含声明为const Int_map& A::getMap()

  const std::map<string,int>& A::getMap()

是什么原因导致这种行为?

类似于相同行为,我还有另一个与std::string有关的问题:

我知道字符串也是C 中的Typedef,并且使用了模板。返回string的函数如何在C 中起作用,typedef map会引发错误?

范围。定义功能时,您不在类A的范围,而是在全局范围中。您需要使用A::Int_map

这是您需要在A::getMap中使用范围操作员的原因。