【发布时间】:2019-07-05 10:01:51
【问题描述】:
以下代码导致以下编译错误:
error: no matching member function for call to 'push'
st.push(ptr);
如果我删除func 中ptr 参数的const,问题就会消失。所以这似乎意味着你不能将常量指针压入堆栈。为什么会这样?如果我尝试将其推入std::queue,它似乎也会给出相同的错误,并且我也怀疑其他容器。
#include <iostream>
#include <stack>
void func(const int *&ptr)
{
std::stack<int *> st;
st.push(ptr);
}
int main(int argc, char const *argv[])
{
int i = 2;
auto ptr = &i;
func(ptr);
}
【问题讨论】:
-
A
const T *不能被隐式转换(并且几乎不应该被显式转换)为T *。您正在尝试将const int *存储到需要转换的int *容器中。 -
它不是“常量指针”,而是指向 const int 的指针
-
决定你的栈是否包含常量对象。如果是这样,那么您只需将指针传递给常量对象就没有困难了。不是,那就不要尝试将指向 const 对象的指针放入其中。
标签: c++ pointers stack constants push