参数传递(non reference parameter)
C++ is a statically typed language. The arguments of every call are checked during compilation.
int gcd(int v1, int v2);
But what happens if the call supplies two arguments of type double ? Is this call legal?
gcd("hello", "world"); // error: wrong argument types gcd(3.14, 6.29); // ok: arguments are converted to int
In the first call, the arguments are of type const char* .
In the second call, because this conversion might lose precision, most compilers will issue a warning. In this case, the call becomes
gcd(3, 6);
-----------------------------------------------------------------------------------------------------------------------------
If the parameter has a nonreference type, then the argument is copied. If the parameter is a reference, then the parameter is just another name for the argument.
We may initialize a pointer to const to point to a non const object but may not use a pointer to non const to point to a const object.
We can call a function that takes a non reference, non const parameter passing either a const or non const argument.
If we make the parameter a const nonreference type:
void fcn(const int i) { /* fcn can read but not write to i */ }
The argument is still passed as a copy so we can pass fcn either a const or non const object.
What may be surprising, is that although the parameter is a const inside the function, the compiler otherwise treats the definition of fcn as if we had defined the parameter as a plain int
void fcn(const int i) { /* fcn can read but not write to i */ } void fcn(int i) {} // error: redefines fcn(int) void fcn(const int &i) {} void fcn(int &i) {} // OK void fcn(const int *i) {} void fcn(int *i) {} // OK void fcn(int * const i) {} void fcn(int *i) {} // error // 从调用者的角度分析,第一个函数只能传递给它非常量,第二个函数是同样的。所以发生重复定义错误。
Copying an argument is not suitable for every situation. Cases where copying doesn't work include:
1、When we want the function to be able to change the value of an argument.
2、When we want to pass a large object as an argument. The time and space costs to copy the object are often too high for real-world applications.
3、When there is no way to copy the object.
In these cases we can instead define the parameters as references or pointers.