如何从函数返回对?
我试图编写一个函数,它将返回函数对,但在编译期间出现错误。
This is the whole file:
#include <iostream>
#include <map>
#include <utility>
using namespace std;
typedef pair<const string, const double> pr;
typedef map<const string,pr > mpr;
mpr mymap;
pr getvalue(const string s)
{
pr pValue;
mpr::iterator iter = mymap.find(s);
if(iter not_eq mymap.end())
{
pValue = (*iter).second;
}
return pValue;
}
int main( )
{
getvalue("test");
}
错误信息:
在/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algobase.h:66包含的文件中,从/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/char_traits.h:41,来自/ usr / lib /gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ios:41,来自/ usr / lib / gcc / x86_64-redhat-linux /4.4.7/../../../../include/c++/4.4.7/ostream:40,来自/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../ ../../../include/c++/4.4.7/iostream:40,from test8.cxx:1:/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../ .. /../../include/c++/4.4.7/bits/stl_pair.h:在成员函数'std :: pair,std :: allocator>,const double>&std :: pair,std :: allocator> ,const double> :: operator =(const std :: pair,std :: allocator>,const double>&)':/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../ .. /../../include/c++/4.4.7/bits/stl_pair.h:68:错误:非静态const成员'const std :: basic_string,std :: allocator> std :: pair,std :: allocator>,const double> :: first',不能使用默认赋值运算符/ usr / lib / gcc / x86_64-redhat-linux / 4.4.7 /../../../../ include / c ++ / 4.4.7 / bits / stl_pair.h:68:error:non-static const member' const double std :: pair,std :: allocator>,const double> :: second',不能使用默认赋值操作符test8.cxx:在函数'pr getvalue(std :: string)'中:test8.cxx:14 :注意:合成方法'std :: pair,std :: allocator>,const double>&std :: pair,std :: allocator>,const double> :: operator =(const std :: pair,std :: allocator >,const double>&)'在这里首先需要
请帮助我。
类型pr
被定义为两个成员都是const
。 一旦声明,变量pValue
就不能在赋值pValue = (*iter).second
,因为它的所有成员都是有效的const。
代码可以修改为(应该编译);
pr getvalue(const string s)
{
mpr::iterator iter = mymap.find(s);
if(iter not_eq mymap.end())
{
return (*iter).second;
}
return pr();
}
链接地址: http://www.djcxy.com/p/66743.html