深度探究C++中的函数重载的用法

2020-01-06 14:34:16王冬梅

虽然可以根据返回类型区分函数,但是无法在此基础上对它们进行重载。仅当 Const 或 volatile 在类中用于应用于类的 this 指针(而不是函数的返回类型)时,它们才用作重载的基础。换言之,仅当 const 或 volatile 关键字遵循声明中函数的参数列表时,重载才适用。
以下示例阐述如何使用重载。

 


// function_overloading.cpp
// compile with: /EHsc
#include <iostream>
#include <math.h>

// Prototype three print functions.
int print( char *s );         // Print a string.
int print( double dvalue );      // Print a double.
int print( double dvalue, int prec ); // Print a double with a
// given precision.
using namespace std;
int main( int argc, char *argv[] )
{
const double d = 893094.2987;
if( argc < 2 )
  {
// These calls to print invoke print( char *s ).
print( "This program requires one argument." );
print( "The argument specifies the number of" );
print( "digits precision for the second number" );
print( "printed." );
exit(0);
  }

// Invoke print( double dvalue ).
print( d );

// Invoke print( double dvalue, int prec ).
print( d, atoi( argv[1] ) );
}

// Print a string.
int print( char *s )
{
cout << s << endl;
return cout.good();
}

// Print a double in default precision.
int print( double dvalue )
{
cout << dvalue << endl;
return cout.good();
}

// Print a double in specified precision.
// Positive numbers for precision indicate how many digits
// precision after the decimal point to show. Negative
// numbers for precision indicate where to round the number
// to the left of the decimal point.
int print( double dvalue, int prec )
{
// Use table-lookup for rounding/truncation.
static const double rgPow10[] = { 
10E-7, 10E-6, 10E-5, 10E-4, 10E-3, 10E-2, 10E-1, 10E0,
10E1, 10E2, 10E3, 10E4, 10E5, 10E6
  };
const int iPowZero = 6;
// If precision out of range, just print the number.
if( prec < -6 || prec > 7 )
return print( dvalue );
// Scale, truncate, then rescale.
dvalue = floor( dvalue / rgPow10[iPowZero - prec] ) *
rgPow10[iPowZero - prec];
cout << dvalue << endl;
return cout.good();
}

前面的代码演示了文件范围内的 print 函数重载。
默认参数不被视为函数类型的一部分。因此,它不用于选择重载函数。仅在默认参数上存在差异的两个函数被视为多个定义而不是重载函数。
不能为重载运算符提供默认参数。
参数匹配
选择重载函数以实现当前范围内的函数声明与函数调用中提供的参数的最佳匹配。如果找到合适的函数,则调用该函数。此上下文中的“Suitable”具有下列含义之一: