C ++对象参考的行为

问题描述 投票:5回答:4

请考虑以下代码段:

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;
     }

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

c++ polymorphism virtual-functions object-reference
4个回答
10
投票

您遇到切片问题。

Window bRef   =*button;

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

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

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


7
投票
  • [aRef具有Window 静态

2
投票
Window bRef=*button;
bRef.Create(); // Output: Base class Window

1
投票
 Window bRef=*button;
 bRef.Create(); // Output: Base class Window
© www.soinside.com 2019 - 2024. All rights reserved.