我在虚函数中有问题:
这是一些代码作为示例:

class A
   {
      public : virtual  void print(void)
           {
              cout<< "A::print()"<<endl;
           }
    };
 class B : public A
    {
      public : virtual void print(void)
           {
               cout<<"B::print()"<<endl;
           }
    };
 class C : public A
    {
      public : void print(void)
            {
               cout<<"C::print()"<<endl;
            }
     };
  int main(void)
     {
         A a,*pa,*pb,*pc;
         B b;
         C c;
         pa=&a;
         pb=&b;
         pc=&c;

         pa->print();
         pb->print();
         pc->print();

         a=b;
         a.print();
         return 0;
       }


结果:
             打印()
             B :: print()
             C :: print()
             打印()

我知道这是一个多态性,并且知道有一个称为虚函数表的表,但是我不知道它是如何实现的,并且

   a=b;
   a.print();


结果是:A :: print()而不是B :: print(),为什么它没有多态性。
谢谢!

最佳答案

a=b;
a.print();


它将打印A::print(),因为a=b会导致对象切片,这意味着a仅获取b的a-subobject。读这个 :


What is object slicing?


注意,运行时多态只能通过指针和引用类型来实现。在上面的代码中,a既不是指针,也不是引用类型:

A * ptr = &b; //syntax : * on LHS, & on RHS
A & ref =  b; //syntax : & on LHS, that is it!

ptr->print(); //will call B::print() (which you've already seen)
ref.print();  //will call B::print() (which you've not seen yet)

关于c++ - C++中对复制对象的动态绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11718070/

10-11 22:56
查看更多