Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我必须从&;更改地图值的类型;至(国际*)及;_C++_Dictionary_Constants - Fatal编程技术网

C++ 为什么我必须从&;更改地图值的类型;至(国际*)及;

C++ 为什么我必须从&;更改地图值的类型;至(国际*)及;,c++,dictionary,constants,C++,Dictionary,Constants,我有一个函数getElement,它返回一个指向映射值的指针 int * getElement(const int &key) const { return (int*)&m.find(key)->second; } 如果我使用例如return&m.find(key)->second,它会创建一个编译错误: 在成员函数“int*A::getElement(const int&)const”中:12:30: 错误:从“常量int*”到“int*”的

我有一个函数
getElement
,它返回一个指向映射值的指针

 int * getElement(const int &key) const {
        return (int*)&m.find(key)->second;
    }
如果我使用例如
return&m.find(key)->second
,它会创建一个编译错误:

在成员函数“int*A::getElement(const int&)const”中:12:30: 错误:从“常量int*”到“int*”的转换无效[-fpermissive]

  • 为什么我必须将
    &m.find(key)->second
    更改为
    (int*)&m.find(key)->second
    ,才能正确编译代码

#包括
#包括
#包括
甲级{
公众:
无效加法元素(常量整数和键、常量整数和值){
m、 安置(关键、价值);
}
int*getElement(常量int&key)常量{
return(int*)&m.find(key)->second;
}
私人:
std::map m;
};
int main()
{
A A;
int值=1;
int键=1;
a、 加法器(键、值);
int*x=a.getElement(1);
std::cout

int * getElement(const int &key) const
是常量,因此您可以将所有数据membre作为常量访问

int*
不同于
const int*

这个函数

int * getElement(const int &key) const
是常量,因此您可以将所有数据membre作为常量访问

int*
const int*

为什么我必须将
&m.find(key)->second
更改为
(int*)&m.find(key)->second

不需要。事实上,这样做可能会产生错误。如果确实要修改映射值,请删除成员函数上的
const
限定符。或者从函数中返回
const int*
而不是
int*

为了澄清这一点,当您将成员函数指定为
const
时,该函数中的
this
指针将成为指向类的
const
实例的指针。这反过来会使其数据成员
const

因此,您的
std::map
getElement
函数中变成了
std::map const
。此外,
const
映射有一个重载,返回一个
const\u迭代器
,因此产生了
const int*

事实上,要小心:
std::map::iterator
不一定是
t*
。所以你不应该返回
int*
const int*
-你应该返回
std::map::iterator
(或
..:const\u iterator

为什么我必须将
&m.find(key)->second
更改为
(int*)&m.find(key)->second

不需要。事实上,这样做可能会产生错误。如果确实要修改映射值,请删除成员函数上的
const
限定符。或者从函数中返回
const int*
而不是
int*

为了澄清这一点,当您将成员函数指定为
const
时,该函数中的
this
指针将成为指向类的
const
实例的指针。这反过来会使其数据成员
const

因此,您的
std::map
getElement
函数中变成了
std::map const
。此外,
const
映射有一个重载,返回一个
const\u迭代器
,因此产生了
const int*

事实上,要小心:
std::map::iterator
不一定是
t*
。所以你不应该返回
int*
const int*
-你应该返回
std::map::iterator
(或
..:const\u iterator