arguments - C++ const 形参和实参的类型问题
ringa_lee
ringa_lee 2017-04-17 15:26:51
0
1
963

最近在学习C++ Primer 5th(英文版), 函数(章节6),P.216。这里有一个例子如下:

voide fcn(const int i) //fcn can read but not write to i。

按照书上自己的定义(P.203),函数的形参和实参的类型必须是匹配的,或者有形参的隐式转换。那么对这个例子来说,我的思路是:

  • 这里是值传递,那么fcn会创建一个实参的拷贝parameter。

  • 如果这个parameter 是const int类型,那么很显然这个复制是不能完成的。(const

  • 因此那么这个parameter 只能是普通的int类型,top_level const被忽略掉了。

我写了一段代码来测试,编译器报错说不能对只读形参操作。

#include <iostream>
using namespace std;
void const_parameter(const int i);
int main(int argc, char const *argv[])
{
    const int a = 1;
    const_parameter(a);
    return 0;
}
void const_parameter(const int i){
    ++i; // try to modify parameter i but failed.
}

我的问题是,为什么这里是只读形参?如果是只读形参,那这个只读形参是怎么接受实参的拷贝的?谢谢!

ringa_lee
ringa_lee

ringa_lee

reply all(1)
黄舟

Looking back at my thoughts just now, I found that there was actually a very big problem in the second step, which confused the initialization and assignment of const. In the process of pass by value, the operation is actually to initialize parameter with argument, not assignment. For const, it is allowed to give an initial value of type const during initialization, such as:

const int i = 10;
const int j = i; //no problem at all!

So the definition of the parameter in the previous function is already very clear. No matter how you convert it, no matter what value is in your argument, it has to be converted into the const int type. This is why i cannot be used. Reason for writing.
I really don’t know how stupid I am if I don’t write programs. . .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template