【问题标题】:what do you mean by base class reference or derived class reference? [closed]基类引用或派生类引用是什么意思? [关闭]
【发布时间】:2022-01-21 07:58:39
【问题描述】:

我对向上转换和向下转换上下文中的基类引用派生类引用感到困惑。

下面代码中&ref有什么用?在reference 中,它被标记为基类引用,并为其分配了一个派生类obj

这背后的概念是什么?

#include <iostream>  
using namespace std;  
class Base  
{  
    public:  
        void disp()  
    {  
        cout << " It is the Super function of the Base class ";  
    }  
};  
  
class derive : public Base  
{  
    public:  
        void disp()  
        {  
            cout << "\n It is the derive class function ";  
        }  
      
};  
  
int main ()  
{  
    // create base class pointer  
    Base *ptr;  
      
    derive obj; // create object of derive class  
    ptr = &obj; // assign the obj address to ptr variable  
      
    // create base class's reference  
     Base &ref = obj;   
    // Or  
    // get disp() function using pointer variable  
      
    ptr->disp();  
    return 0;  
}  

【问题讨论】:

  • 你知道什么是引用吗?你知道什么是基类和派生类吗?
  • @bolov 是的,先生,我知道这些条款
  • 那有什么困惑呢?基类引用是对基类类型的引用。
  • “这背后的概念是什么?”——你能详细解释一下你所说的“这个”是什么意思吗?我认为“this”的意思是“标记为基类引用,派生类 obj 被分配给该引用”,但其背后的概念是:派生类对象被分配给基类引用。也许可以解释为什么这对您来说似乎是错误的?否则,您可能不得不等到有人猜出您的想法。

标签: c++ class casting reference


【解决方案1】:

虽然不清楚你在问什么,但我会尝试澄清一些关于这个主题的基础知识。

首先,reference 引用其他对象。引用本身并不是一个对象。那么让我们来看一些例子:

int n = 10;
int &r = n; // Here r is a reference to an int object

同样在你的代码 sn-p 中,你写的时候:

derive obj; //obj is an object of type derive
Base &ref = obj;  // ref is bound to the Base part of derive
Base *ptr = &obj; // ptr points to the Base part of derive

在上面的例子中,有两点需要注意:

  1. 因为派生对象包含与其基类对应的子部分,我们可以使用派生类型的对象,就好像它是其基类型的对象一样。特别是,我们可以将基类引用或指针绑定到派生对象的基类部分,如上所述。这种转换称为派生到基础转换。
  2. 名为ptr 的对象的静态类型Base*。而同一对象ptr动态类型derive*。所以静态类型和动态类型不同。

另外,请注意我们能够/被允许写:

Base *ptr = &obj;

因为$11.2/5 states -

如果基类是可访问的,则可以隐式将指向派生类的指针转换为指向该基类的指针

现在回到你的问题:

&ref 有什么用?

class Base  
{  
    public:  
        virtual void disp()  //VIRTUAL kewword USED HERE
    {  
        cout << " It is the Super function of the Base class ";  
    }  
};

如果在你的代码 sn-p 中,方法 disp()virtual 如上面修改的 sn-p 所示,那么我们可以使用 refptr 来调用derive 类的方法 disp()。这是因为:

根据virtual function documentation

虚函数是可以为其他派生类重新定义的成员函数,可以保证编译器会为对应的派生类对象调用重新定义的虚函数 strong>,即使您使用对象基类的指针引用调用该函数。

所以当我们写的时候:

ref.disp(); //this calls the derive class method disp() at runtime
ptr->disp(); //this calls the derive class method disp() at runtime

上面的result是在运行时调用派生类的函数disp,我们看到It is the derive class function打印在控制台上。

所以基本上用途是我们可以在运行时决定调用哪个方法(无论是 Base 的还是派生的)。

查看程序的输出here

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2019-04-05
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多