☰
详解C++编程中向函数传递引用参数的用法
2026/10/6 3:30:03 网站建设 项目流程

引用类型的函数参数
向函数传递引用而非大型对象的效率通常更高。 这使编译器能够在保持已用于访问对象的语法的同时传递对象的地址。 请考虑以下使用了 Date 结构的示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

// reference_type_function_arguments.cpp

structDate

{

shortDayOfWeek;

shortMonth;

shortDay;

shortYear;

};

// Create a Julian date of the form DDDYYYY

// from a Gregorian date.

longJulianFromGregorian( Date& GDate )

{

staticintcDaysInMonth[] = {

31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

};

longJDate = 0;

// Add in days for months already elapsed.

for(inti = 0; i < GDate.Month - 1; ++i )

JDate += cDaysInMonth[i];

// Add in days for this month.

JDate += GDate.Day;

// Check for leap year.

if( GDate.Year % 100 != 0 && GDate.Year % 4 == 0 )

JDate++;

// Add in year.

JDate *= 10000;

JDate += GDate.Year;

returnJDate;

}

intmain()

{

}

前面的代码显示通过引用传递的结构的成员是通过成员选择运算符 (.) 访问的,而不是通过指针成员选择运算符 (–>) 访问的。
尽管作为引用类型传递的参数遵循了非指针类型的语法,但它们仍然保留了指针类型的一个重要特征:除非被声明为 const,否则它们是可以修改的。 由于上述代码的目的不是修改对象 GDate,因此更合适的函数原型是:

1

longJulianFromGregorian(constDate& GDate );

此原型将确保函数 JulianFromGregorian 不会更改其参数。
任何其原型采用引用类型的函数都能接受其所在位置的相同类型的对象,因为存在从 typename 到 typename& 的标准转换。

引用类型函数返回
可将函数声明为返回引用类型。 做出此类声明原因有:

  • 返回的信息是一个返回引用比返回副本更有效的足够大的对象。
  • 函数的类型必须为左值。
  • 引用的对象在函数返回时不会超出范围。

就像通过引用传递大型对象 to 函数或返回大型对象 from 函数可能更有效。 引用返回协议使得不必在返回前将对象复制到临时位置。

当函数的计算结果必须为左值时,引用返回类型也可能很有用。 大多数重载运算符属于此类别,尤其是赋值运算符。 重载运算符在重载运算符中有述。
示例
请考虑 Point 示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

// refType_function_returns.cpp

// compile with: /EHsc

#include <iostream>

usingnamespacestd;

classPoint

{

public:

// Define "accessor" functions as

// reference types.

unsigned& x();

unsigned& y();

private:

// Note that these are declared at class scope:

unsigned obj_x;

unsigned obj_y;

};

unsigned& Point :: x()

{

returnobj_x;

}

unsigned& Point :: y()

{

returnobj_y;

}

intmain()

{

Point ThePoint;

// Use x() and y() as l-values.

ThePoint.x() = 7;

ThePoint.y() = 9;

// Use x() and y() as r-values.

cout <<"x = "<< ThePoint.x() <<"\n"

<<"y = "<< ThePoint.y() <<"\n";

}

输出

1

2

x = 7

y = 9

请注意,函数x 和 y 被声明为返回引用类型。 这些函数可在赋值语句的每一端上使用。
另请注意在 main 中,ThePoint 对象停留在范围中,因此其引用成员仍处于活动状态,可以安全地访问。
除以下情况之外,引用类型的声明必须包含初始值设定项:

  • 显式 extern 声明
  • 类成员的声明
  • 类中的声明
  • 函数的参数或函数的返回类型的声明

返回局部变量地址时的注意事项

如果在局部范围中声明某个对象,则该对象会在函数返回时销毁。 如果函数返回对该对象的引用,则当调用方尝试使用 null 引用时,该引用可能会在运行时导致访问冲突。

1

2

3

4

5

6

7

// C4172 means Don't do this!!!

Foo& GetFoo()

{

Foo f;

...

returnf;

}// f is destroyed here

编译器会在这种情况下发出警告:警告 C4172: 返回局部变量或临时变量的地址。 在简单程序中,如果调用方在覆盖内存位置之前访问引用,则有时可能不会发生访问冲突。 这纯属运气。 请注意该警告。

对指针的引用
声明对指针的引用的方式与声明对对象的引用差不多。声明对指针的引用将生成一个可像常规指针一样使用的可修改值。
以下代码示例演示了使用指向指针的指针与使用对指针的引用之间的差异。
函数 Add1 和 Add2 在功能上是等效的(虽然它们的调用方式不同)。二者的差异在于,Add1 使用双间接寻址,而 Add2 利用了对指针的引用的便利性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

// references_to_pointers.cpp

// compile with: /EHsc

#include <iostream>

#include <string>

// STL namespace

usingnamespacestd;

enum{

sizeOfBuffer = 132

};

// Define a binary tree structure.

structBTree {

char*szText;

BTree *Left;

BTree *Right;

};

// Define a pointer to the root of the tree.

BTree *btRoot = 0;

intAdd1( BTree **Root,char*szToAdd );

intAdd2( BTree*& Root,char*szToAdd );

voidPrintTree( BTree* btRoot );

intmain(intargc,char*argv[] ) {

// Usage message

if( argc < 2 ) {

cerr <<"Usage: Refptr [1 | 2]"<<"\n";

cerr <<"\nwhere:\n";

cerr <<"1 uses double indirection\n";

cerr <<"2 uses a reference to a pointer.\n";

cerr <<"\nInput is from stdin.\n";

return1;

}

char*szBuf =newchar[sizeOfBuffer];

if(szBuf == NULL) {

cerr <<"Out of memory!\n";

return-1;

}

// Read a text file from the standard input device and

// build a binary tree.

//while( !cin.eof() )

{

cin.get( szBuf, sizeOfBuffer,'\n');

cin.get();

if(strlen( szBuf ) ) {

switch( *argv[1] ) {

// Method 1: Use double indirection.

case'1':

Add1( &btRoot, szBuf );

break;

// Method 2: Use reference to a pointer.

case'2':

Add2( btRoot, szBuf );

break;

default:

cerr <<"Illegal value '"

<< *argv[1]

<<"' supplied for add method.\n"

<<"Choose 1 or 2.\n";

return-1;

}

}

}

// Display the sorted list.

PrintTree( btRoot );

}

// PrintTree: Display the binary tree in order.

voidPrintTree( BTree* MybtRoot ) {

// Traverse the left branch of the tree recursively.

if( btRoot->Left )

PrintTree( btRoot->Left );

// Print the current node.

cout << btRoot->szText <<"\n";

// Traverse the right branch of the tree recursively.

if( btRoot->Right )

PrintTree( btRoot->Right );

}

// Add1: Add a node to the binary tree.

// Uses double indirection.

intAdd1( BTree **Root,char*szToAdd ) {

if( (*Root) == 0 ) {

(*Root) =newBTree;

(*Root)->Left = 0;

(*Root)->Right = 0;

(*Root)->szText =newchar[strlen( szToAdd ) + 1];

strcpy_s((*Root)->szText, (strlen( szToAdd ) + 1), szToAdd );

return1;

}

else{

if(strcmp( (*Root)->szText, szToAdd ) > 0 )

returnAdd1( &((*Root)->Left), szToAdd );

else

returnAdd1( &((*Root)->Right), szToAdd );

}

}

// Add2: Add a node to the binary tree.

// Uses reference to pointer

intAdd2( BTree*& Root,char*szToAdd ) {

if( Root == 0 ) {

Root =newBTree;

Root->Left = 0;

Root->Right = 0;

Root->szText =newchar[strlen( szToAdd ) + 1];

strcpy_s( Root->szText, (strlen( szToAdd ) + 1), szToAdd );

return1;

}

else{

if(strcmp( Root->szText, szToAdd ) > 0 )

returnAdd2( Root->Left, szToAdd );

else

returnAdd2( Root->Right, szToAdd );

}

}

用法:Refptr [1 | 2]

其中:
1 使用双间接寻址
2 使用对指针的引用。输入来自 stdin。


需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询