首页 > 解决方案 > 比如,虚函数我们可以在 C++ 中创建一个虚拟变量吗

问题描述

当基类指针指向它的派生类的对象并且如果函数被覆盖时,我们使用虚函数来解决问题。这样我们就可以使用指针访问派生类自己的函数了。像这样,我在想,如果有一种方法可以应用于变量中的虚拟关键字,那么我们可以使用指针访问派生类中变量的最新版本。

#include <iostream>
using namespace std;
class base
{
public:
int x;//but what about this , if we add virtual keyword here.
    //it will give error if trying to do so .
    //but can you tell me what can i do if i want to make use of it as virtual function
    //if not please tell me why
virtual void display(void) //to call the recent version of display function we make use of virtual here
{
    cout << "base\n";
}
};
class derived : public base
{
public:
int x;
void display(void)
{
    cout << "derived\n";
}
};
int main(void)
{
    base *p;
    base ob1;
    derived ob2;
    p=&ob2;
    p->x=100;//here i want to set 100 to the x of derived class not that x which has been inherited
            //But it sets to the x of base class which i dont wanted
    p->display();//here we can access the latest version of display function in derived class
    return 0;
}

拜托,没有人问我为什么要这样做。我没有任何打算在我的真实代码中这样做。我问他的好奇心。

标签: c++virtual-functions

解决方案


不,您不能virtual用于字段,只能用于方法。

但是,您可以通过创建一个返回字段引用的函数来模拟它:

class Base
{
private:
    int x;

public:
    virtual int& X() { return x; }
};

class Derived : public Base
{
private:
    int x;

public:
    virtual int& X() override { return x; }
};

int main()
{
    Derived d;
    Base* b = &d;

    b->X() = 100; // will set d's x
}

推荐阅读