考虑以下代码段:

class Window // Base class for C++ virtual function example
     {
       public:
          virtual void Create() // virtual function for C++ virtual function example
          {
               cout <<"Base class Window"<<endl;
          }
     };

     class CommandButton : public Window
     {
       public:
          void Create()
          {
              cout<<"Derived class Command Button - Overridden C++ virtual function"<<endl;
          }
     };

     int main()
     {
        Window *button = new   CommandButton;
        Window& aRef = *button;
        aRef.Create(); // Output: Derived class Command Button - Overridden C++ virtual function
        Window bRef=*button;
        bRef.Create(); // Output: Base class Window

        return 0;
     }

aRef bRef 都被分配了 * button ,但是为什么两者的输出不同。
分配给引用类型和非引用类型有什么区别?

最佳答案

您遇到切片问题。

Window bRef   =*button;

在这里,bRef不是引用,而是对象。当您将派生类型分配给bRef时,就将派生部分切开,只剩下一个由CommandButton构造的Window对象。

发生的情况是,在上述语句中,使用编译器为类Window生成的拷贝构造函数创建了bRef。该构造函数所做的全部工作就是将成员元素从RHS复制到新构造的对象。由于该类不包含任何成员,因此没有任何 react 。

附带说明:具有虚拟成员的类也应具有虚拟析构函数。

09-26 21:02
查看更多