const B和const A *不兼容,即使B别名为A * [英] const B and const A* are incompatible, even when B is aliased to A*
问题描述
为什么当 B <时,
const B
和 const A *
不能区分? / code>类型定义为 A *
?编译此简单示例时:
Why aren't const B
and const A*
indistinguishable, when B
is typedef'ed to A*
? When compiling this simple example:
struct A {};
typedef A* B;
void f1(const A* a1);
void f2(const B a2);
int main()
{
const A a;
f1(&a);
f2(&a);
}
我得到以下编译器输出(G ++ 6.3.1):
I get the following compiler output (G++ 6.3.1):
test.cpp: In function ‘int main()’:
test.cpp:12:8: error: invalid conversion from ‘const A*’ to ‘B {aka A*}’ [-fpermissive]
f2(&a);
请注意,调用 f1
很好(因为& a
是-一个 A *
),但 f2
不是,即使在我看来 const B
应该等同于 const A *
。
Note that the call to f1
is fine (since &a
is-an A*
), but f2
is not, even though const B
seems to me like it should be equivalent to const A*
.
推荐答案
const B
表示 A * const
本身就是指针,但是它所指向的对象不是常数。
const B
means A * const
that is the pointer itself is a constant but the object pointed to by the pointer is not constant.
另一方面, const A *
表示指针本身不是常量,而是指针所指向的对象。指针是常量。
On the other hand const A *
means that the pointer itself is not constant but the object pointed to by the pointer is constant.
所以 const B
就是 A * const
不是 const A * $code>
可以写
typedef const A* B;
void f1(const A* a1);
void f2( B a2);
这篇关于const B和const A *不兼容,即使B别名为A *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!