gpt4 book ai didi

c++ - 关于 C++ 中常量的隐式转换

转载 作者:行者123 更新时间:2023-11-30 01:42:46 26 4
gpt4 key购买 nike

#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);
}

为什么编译上述代码时没有任何错误/警告?

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)。

关于c++ - 关于 C++ 中常量的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com