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
中使用范围操作员的原因。