愚弄c ++编译器.将int而不是cont int传递给函数

Has*_*eem -5 c++ compiler-construction int

我如何将int传递给期望const int函数.

或者有没有办法修改cont int值?

编辑:我之前应该提到过,我正在使用ccs c编译器来编程pic微控制器.fprintf函数将常量流作为其第一个参数.它只接受一个常量int并抛出一个编译错误,否则"Stream必须是有效范围内的常量.".

编辑2:Stream是一个常量字节.

jua*_*nza 9

const完全忽略函数参数列表中的顶级,因此

void foo(const int n);
Run Code Online (Sandbox Code Playgroud)

与...完全相同

void foo(int n);
Run Code Online (Sandbox Code Playgroud)

所以,你只是通过了int.

唯一的区别在于函数定义,在第一个示例中,在第二个示例中nconst可变的.因此,这个特殊内容const可以看作是一个实现细节,应该在函数声明中避免.例如,这里我们不想修改n函数内部:

void foo(int n); // function declaration. No const, it wouldn't matter and might give the wrong impression

void foo(const int n) 
{
  // implementation chooses not to modify n, the caller shouldn't care.
}
Run Code Online (Sandbox Code Playgroud)