[Notes] Call for functions with reference parameters

xiaoxiao2021-03-06  40

THE C Program Laguage (Special Edition) Chapter 5 Sixty exercise, the topic is as follows: Define Function F (Char &), after the parameters 'a', 49, 3300 , C, UC, SC call them as parameters, where C is Char, uc is unsigned char, SC is Signed Char. What is legal? Which calls will lead to the compiler to introduce temporary variables?

The solution procedure is as follows. Compiled in VC . Net 2003, and give the compilation error message after the error statement.

Void F (Char CH)

{COUT << "f (char):" << ch << endl;}

Void G (Char & Ch)

{COUT << "G (Char &):" << ch << Endl;}

Void H (Const Char & Ch)

{COUT << "h (const char &):" << ch << endl;

int main ()

{

CHAR C = 'b';

UNSIGNED CHAR UC = 'C';

Signed char SC = 'd';

f ('a');

g ('a'); // error: Not a reference to "const" can't be bound to non-LValue

h ('a');

f (49);

g (49); // Error: Not a reference to "const" can't be bound to non-LValue

h (49);

f (3300); // Warning: "Parameters": Truncation constant value

g (3300); // error: Not a reference to "const" can't be bound to non-LValue

H (3300); // Warning: "Parameters": Truncation constant value

f (c);

g (c);

H (c);

f (uc);

g (uc); // error: Not a reference to "const" can't be bound to non-LValue

H (UC);

f (sc);

g (sc); // error: Not a reference to "const" can't be bound to non-LValue

H (sc);

Return 0;

}

Analysis of error:

The parameter of the function is a reference. Therefore, the actual gateway will be the initialization value of the shape value when the function is called. Here, the arguments are 'A', 49, 3300, C, UC, SC.

The following content is extracted from the book. To ensure that a reference is bind to an object, it must be initialized. A left value is an object that can get its address. (1) Ordinary references, shapes such as T &, must initialize it with a left value of T type. (2) References to constant types, shapes such as Const T &, and its initialization value is not necessarily a left value, or even Types. If the initialization value is not T type, there will be the following work: first make an implicit conversion to the T type when necessary; then store the conversion result into a T-type temporary variable; finally this temporary variable is used to reference this reference Be initialized.

g ('a'); g (49); G (3300); the reason for error, violates subsection (1). 'A', 49, 3300, etc. are not a left value.

G (UC); G (SC); the reason for an error is that the type of initialization value is wrong. It is also a violation of subsection (1). H (const t &), temporary variables are generated with 'A', 49, C, UC, and SC call functions. 3300 has exceeded the maximum of the CHAR type, so it will be wrong.

转载请注明原文地址:https://www.9cbs.com/read-53056.html

New Post(0)