C ++对象引用的行为 [英] Behavior of C++ Object Reference

查看:115
本文介绍了C ++对象引用的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码段:

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 都被分配了 *按钮,但是为什么两个输出是不同的. 分配给引用类型和非引用类型有什么区别?

Both aRef and bRef get assigned *button, but why are the two output different. What is the difference between assigning to Reference type and non Reference type?

推荐答案

您遇到了切片问题.

Window bRef   =*button;

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

Here bRef is not a reference but an object. When you assign a derived type onto bRef you are slicing the derived part off leaving you with just a Window object constructed form a CommandButton.

正在发生的事情是,在上面的语句中使用编译器为类Window生成的副本构造函数创建了bRef.该构造函数所做的全部工作就是将成员元素从RHS复制到新构造的对象.由于该班级没有成员,所以什么也没发生.

What is happening is that bRef is created in the above statement using the compiler generated copy constructor for the class Window. All this constructor does is copy member elements from the RHS to the newly constructed object. Since the class contains no members nothing is happening.

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

On a side note: A class with virtual members should also have a virtual destructor.

这篇关于C ++对象引用的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆