繁体   English   中英

如何将整个数组指针作为 const 传递,以使值无法更改? C++

[英]How do I pass an entire array pointer as const such that the values cannot be changed? C++

如何将整个数组指针作为 const 传递,以使值无法更改? 我将一个数组传递给 function,如下所示:

double myArr[] { 1, 2, 3, 4, 5 };
double* pArr = myArr;

double myVal = MyFunc(pArr, 5);

MyFunc 的 header 现在是:

MyFunc(double* pArr, int length)

我想确保 function 根本无法修改数组内的值。

我该怎么做呢?

将您的 function 签名更改为:

MyFunc(double const* pArr, int length);

请注意,这相当于:

MyFunc(const double* pArr, int length)

您更喜欢哪一个是纯粹的口味问题(我更喜欢第一个,因为我发现它更具可读性——它是pArr中的项目是 const,而不是指针本身)。

只需让 MyFunc 为其 arguments 取(const double *pArr, int length)

您可以通过 const 指针传递它,

MyFunc(const double* const pArr, int length); // pArr or content of pArr will not change

如果您可以自由传递myArr然后通过引用传递它:

MyFunc(const double (&arr)[length]); // where length is known at compile time

将参数作为 const 指针传递。 function 签名将如下所示:

double MyFunc(const double* arr, size_t count);

如何将整个数组指针作为 const 传递?

去做就对了!

MyFunc(const double* pArr, int length)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM