Home > Back-end >  Virtual functions of polymorphic inheritance run results as follows, please explain
Virtual functions of polymorphic inheritance run results as follows, please explain

Time:10-07

# include "StdAfx. H"
#include
#include
#include
using namespace std;

If # 1
Class A
{
Public:
Void foo ()
{
Printf (" 1 \ n ");
}
Virtual void fun ()
{
Printf (" 2 \ n ");
}
};
Class B: public A
{
Public:
Void foo ()
{
Printf (" 3 \ n ");
}
Void fun ()
{
Printf (" 4 \ n ");
}
};
Int main (void)
{
A, A.
B B;
B * PTR=NULL;
PTR=(B *) & amp; a;
PTR - & gt; Foo ();
PTR - & gt; Fun ();
getchar();
return 0;
}
As application, operation results for
3
2
Don't understand why there are such result, strives for the great god

CodePudding user response:

Very magical, unexpectedly someone so using polymorphism,

The correct method is:
A * PTR=& amp; B;
P - & gt; Fun ();

CodePudding user response:

You use methods are dangerous, can turn a subclass object when the superclass object to make, don't put the superclass object when a subclass object,

CodePudding user response:

I know the correct method of use is
A * PTR=& amp; B;
P - & gt; Fun ();

Now just want to know why the result is
Why
B * PTR=(B *) & amp; a; PTR - & gt; Call to the derived class method foo, and PTR - & gt; Fun () calls to the base class method

CodePudding user response:

The
reference 3 floor su_day response:
I know the correct method of use is
A * PTR=& amp; B;
P - & gt; Fun ();

Now just want to know why the result is
Why
B * PTR=(B *) & amp; a; PTR - & gt; Call to the derived class method foo, and PTR - & gt; Fun is () call to a base class method


Foo is a virtual function, compile time depending on the type of the pointer that determine the call B: : foo.
Fun is a virtual function, according to a pointer to the object to determine which function calls;

Have no you so, your thinking is different,

CodePudding user response:

I understand such as

A function pointer is independent of the object
So even if
B * PTR=NULL;
PTR - & gt; Foo ();//as long as don't to class member variables, there is no problem


But
PTR=(B *) & amp; a;//parent of A virtual function table was originally A instance of the
So call in A fun ();

But it's dangerous, LZ still don't write

CodePudding user response:

The parent class defines the virtual function
Virtual void fun ();
A subclass of the same function
Void fun (); Is also a virtual function, regardless of the virtual keyword,

Pay attention to the c + + rules of the game,
  • Related