下面的代码会导致以下编译错误:
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);
}
最佳答案
const 指针的目的是确保指向的对象不能被修改(至少不能通过这个指针)。
如果在将指针压入堆栈时可以将 const int*
转换为 int*
,则可以通过弹出非 const 指针来更改对象。这就是此代码无法编译的原因。
解决方法是让栈成为const指针的栈
void func(const int *&ptr)
{
std::stack<const int *> st;
st.push(ptr);
}
现在这还不够:您的问题会将错误消息转移给调用者。你可以解决这个问题:
int main(int argc, char const *argv[])
{
int i = 2;
const int* ptr = &i; // <------ not auto
func(ptr);
}
为什么?因为该函数需要对 const 指针的引用作为参数。传递普通指针 ptr
不允许构建对 const 指针的引用。
如果您按值而不是按引用传递指针,则无论 ptr
是否为 const 都有效,因为允许编译器将非 const 指针值隐式转换为 const 值。
关于c++ - 将常量指针推送到 std::stack<T *> 会产生编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54638530/