相关疑难解决方法(0)

在标题中用作函数参数的"原始"类型前面删除"const"是否更好?

在代码审查过程中,我的一位同事向我提到,在标题中用作函数参数的"原始类型"前面的"const"是没有意义的,他建议删除这些"const".在这种情况下,他建议仅在源文件中使用"const".原始类型表示诸如"int","char","float"等类型.

以下是示例.

example.h文件

int ProcessScore(const int score);
Run Code Online (Sandbox Code Playgroud)

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}
Run Code Online (Sandbox Code Playgroud)

他的建议如下:

example.h文件

int ProcessScore(int score);  // const is removed here.
Run Code Online (Sandbox Code Playgroud)

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}
Run Code Online (Sandbox Code Playgroud)

但我有点困惑.通常,用户只会查看标题,因此如果标题和源文件之间存在不一致,则可能会导致混淆.

有人可以给出一些建议吗?

c++ const header primitive-types

48
推荐指数
4
解决办法
4875
查看次数

为什么在头文件中的函数声明中对于通过值传递的参数不需要const?

我最近在阅读关于const在C中使用关键字作为函数参数的方法以及使用它的方法已经在时间和内容中const提到关键字在C中用于变量并被接受为正确答案.在这篇文章中,有一点提到了这一点

永远不要const在函数原型中使用值传递的参数.它没有意义,因此只是'噪音'.

我用这种方式,它适用于我,但我不知道为什么这是通过值传递的参数的噪音,但不是参考传递的参数的噪音(更恰当的是C中的指针值,因为没有pass by value和的概念pass by reference在C).因此,当我将指针作为函数参数传递并使用const关键字时,通过这种解释; 我必须为头文件中的声明和C文件中的定义执行此操作,但我不需要const在声明(头文件)中使用关键字作为非指针参数,并且仅在定义函数时使用它C档.

有什么解释吗?

c pointers const header-files

5
推荐指数
2
解决办法
1273
查看次数

标签 统计

const ×2

c ×1

c++ ×1

header ×1

header-files ×1

pointers ×1

primitive-types ×1