gpt4 book ai didi

c++ - C++中 `int* const& x`和 `int* const x`的区别

转载 作者:行者123 更新时间:2023-12-04 07:54:16 26 4
gpt4 key购买 nike

我已经阅读了按值传递、按引用传递和按常量引用传递(指针)之间的区别,但我不明白后者与仅传递常量指针之间的区别。举个例子,有什么区别

int PI = 3;

int* getArg(int* const& x){
x = Π
return x;
}

int main() {

}
int PI = 3;

int* getArg(int* const x){
x = Π
return x;
}

int main() {

}
这两个导致相同的 error: assignment of read-only parameter 'x' .

最佳答案

如果您很清楚按值和按引用传递变量,那么请尝试将复杂类型分解为多个部分,以帮助理解发生了什么:

using PointerToInt = int*;
using ConstPointerToInt = PointerToInt const;

int* getArg_v1(ConstPointerToInt x) {
x = Π // it's const by value so you're not allowed to change it
return x;
}

int* getArg_v2(ConstPointerToInt& x) {
x = Π // it's const by reference so you're not allowed to change it
return x;
}

关于c++ - C++中 `int* const& x`和 `int* const x`的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66785156/

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