关于 C++ 中常量的隐式转换
Implicit conversion regarding constness in c++
#include <iostream>
int foo(const char* keke) {
std::cout << keke;
return 0;
}
int main()
{
char* keke = new char(10);
char* const haha = keke;
return foo(haha);
}
为什么上面的代码编译的时候没有errors/warning?
haha
的类型是char* const
,而foo
只接收const char*
类型的参数。 char* const
可以隐式转换为 const char*
吗?
是的。它被称为 qualification conversions (隐式转换之一):
(强调我的)
A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).
"More" cv-qualified means that
a pointer to unqualified type can be converted to a pointer to const;
...
表示char*
可以隐式转换为const char*
。
const
指针本身的限定符在这里无关紧要,参数 keke
本身被声明为按值传递,从 haha
复制参数就可以了(即 const
指针;char* const
)。
#include <iostream>
int foo(const char* keke) {
std::cout << keke;
return 0;
}
int main()
{
char* keke = new char(10);
char* const haha = keke;
return foo(haha);
}
为什么上面的代码编译的时候没有errors/warning?
haha
的类型是char* const
,而foo
只接收const char*
类型的参数。 char* const
可以隐式转换为 const char*
吗?
是的。它被称为 qualification conversions (隐式转换之一):
(强调我的)
A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).
"More" cv-qualified means that
a pointer to unqualified type can be converted to a pointer to const;
...
表示char*
可以隐式转换为const char*
。
const
指针本身的限定符在这里无关紧要,参数 keke
本身被声明为按值传递,从 haha
复制参数就可以了(即 const
指针;char* const
)。