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

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


// declaration_matching1.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
void func( int i )
{
  cout << "Called file-scoped func : " << i << endl;
}

void func( char *sz )
{
  cout << "Called locally declared func : " << sz << endl;
}

int main()
{
  // Declare func local to main.
  extern void func( char *sz );

  func( 3 );  // C2664 Error. func( int ) is hidden.
  func( "s" );
}

前面的代码显示函数 func 中的两个定义。由于 char * 语句,采用 main 类型的参数的定义是 extern 的本地定义。因此,采用 int 类型的参数的定义被隐藏,而对 func 的第一次调用出错。
对于重载的成员函数,不同版本的函数可能获得不同的访问权限。它们仍被视为在封闭类的范围内,因此是重载函数。请考虑下面的代码,其中的成员函数 Deposit 将重载;一个版本是公共的,另一个版本是私有的。
此示例的目的是提供一个 Account 类,其中需要正确的密码来执行存款。使用重载可完成此操作。
请注意,对 Deposit 中的 Account::Deposit 的调用将调用私有成员函数。此调用是正确的,因为 Account::Deposit 是成员函数,因而可以访问类的私有成员。


// declaration_matching2.cpp
class Account
{
public:
  Account()
  {
  }
  double Deposit( double dAmount, char *szPassword );

private:
  double Deposit( double dAmount )
  {
   return 0.0;
  }
  int Validate( char *szPassword )
  {
   return 0;
  }

};

int main()
{
  // Allocate a new object of type Account.
  Account *pAcct = new Account;

  // Deposit $57.22. Error: calls a private function.
  // pAcct->Deposit( 57.22 );

  // Deposit $57.22 and supply a password. OK: calls a
  // public function.
  pAcct->Deposit( 52.77, "pswd" );
}

double Account::Deposit( double dAmount, char *szPassword )
{
  if ( Validate( szPassword ) )
   return Deposit( dAmount );
  else
   return 0.0;
}

 



注:相关教程知识阅读请移步到C++教程频道。