【发布时间】:2020-08-12 05:02:58
【问题描述】:
我有以下基本代码:
基本代码
int main()
{
int i = 1;
const int* p = &i;
int* q = &i;
test_ptr(p);
test_ptr(q);
}
谁能解释为什么第一个和第三个示例可以使用上述基本代码,而第二个则不能?
示例实现test_ptr()
示例 1 有效。这是可行的,因为具有指向 const int 的指针的函数也将接受指向非 const int 的指针(但不是相反)
void test_ptr(const int* p) // pointer to const int
{
}
示例 2 不起作用。我真的不明白为什么。它仍然是指向 const int 的指针,但作为引用传递。这与我对引用如何工作的理解不一致。当我将非常量指针传递给函数时,它会失败。
void test_ptr(const int*& p) // reference to pointer to const int
{
}
示例 3 再次运行,我完全迷失了。那么,如果情况 2 不起作用,为什么我将 int* 表示为 typedef 会再次起作用?
typedef int* int_ptr;
void test_ptr(const int_ptr& p) // like case 2 but int* expressed as typedef
{
}
当我使用指针指向指针而不是引用指针时也会发生这种情况。
编辑:示例 3 需要一个不同的 main 函数来使用 typedef:
int main()
{
int i = 1;
const int_ptr p = &i; // use typedef here
int_ptr q = &i; // use typedef here
test_ptr(p);
test_ptr(q);
}
【问题讨论】:
-
示例 2 不起作用是什么意思?它可以与正确的呼叫类型一起使用。见a live demo。
-
void test_ptr(int const* const& p)将是 2 的正确签名。指针也需要为const。 -
.... 当您将
p传递给它时,3 不起作用,因为int_ptr是非常量的。const int_ptr&表示int* const&不是int const*&。 -
this 回答你的问题了吗?
-
@TedLyngmo 没关系。任何有更好建议的人都可以提出他们的建议。一个不完美的答案总比没有好。感谢您的帮助。
标签: c++ pointers reference arguments constants