我应该声明一个永远不会更改为const变量的参数?

编程入门 行业动态 更新时间:2024-10-11 13:19:24
本文介绍了我应该声明一个永远不会更改为const变量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 对函数参数使用'const'

例如,

void Func(int para);

如果我知道我不想更改Func我改为声明para作为const int来保证?即

If I know I don't want to change para's value in Func(...), should I instead declare para as "const int" to guarantee that? i.e.

void Func(const int para);

BTW,我认为

void Func(const int &para);

有时候因为const int&通常由底层指针实现,因此它基本上等效于

is not an appropriate alternative sometimes because const int& is usually implemented by underlying pointer, thus it is essentially equivalent to

void Func(const int *p_para);

本书C ++编码标准:101规则p31说void Func ;是坏的,因为它会头痛读者的头文件。我不知道是否...

The book "C++ Coding Standards: 101 Rules" p31 says that "void Func(const int para);" is bad as it will "confuse" the readers of the header files. I'm not sure though...

我想一个很好的解决方案是声明为void Func(int para);并在实现它时使用void Func(const int para){...}。我发现在void Func(const int para);将被编译器默认删除...

After thought it over, I think a good solution is to declare it as "void Func(int para);" and use "void Func(const int para) {...}" when implement it. I find that the word "const" in "void Func(const int para);" will be silently dropped by the compiler...

推荐答案

如果你这么做(有些人做)把const放在定义中(在这里它是有用的),而不是声明(它是噪声,它不会影响调用者)。

If you do this at all (and some people do) then you should put the const in the definition (where it is useful) but not the declaration (where it is noise, it doesn't affect the caller).

p>

So:

void F(int param); ... void F(int const param) { ... }

更多推荐

我应该声明一个永远不会更改为const变量的参数?

本文发布于:2023-11-13 11:07:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:永远不会   变量   声明   参数   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!