Which function is called?

类别:编程语言 点击:0 评论:0 推荐:

class b
{
public:
  virtual void mf( int p ) ;
} ;
void b::mf( int p )
{
  cout << "member function mf in b called, "
       << "value of parameter is " << p << endl ;
}

class d : public b
{
public:
  void mf( double p ) ;
} ;
void d::mf( double p )
{
  cout << "member function mf in d called, "
       << "value of parameter is " << p << endl ;
}

void main()
{
  b *ptr ;
  ptr = new d ;
  ptr->mf( 1.5 ) ;
}

Think what's the output. The output is:
member function mf in b called, value of parameter is 1


The decision process by the complier is as following:

1. In main function, a pointer ptr is declared whose type is b*.
2. An object d of class d is allocated and ptr point to the object d.
3. As the type of ptr is b*, the program begin to find the function void mf(double p) defined in class b.
4. There is no function void mf(double p) in class b, the program convert float(1.5) to int(1), and then call the function void mf(int p).

本文地址:http://com.8s8s.com/it/it22230.htm