像,虚拟函数我们可以在 C++ 中使变量成为虚拟的吗? [英] Like, virtual function can we make a variable virtual in c++

查看:18
本文介绍了像,虚拟函数我们可以在 C++ 中使变量成为虚拟的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when a base class pointer points to the object of it's derived class and if a function being overridden we use virtual function to solve the problem . So that we can access the own function of derived class using the pointer. Like this , i was thinking that if there a way which can be applied on virtual keyword in variable , so that we can access the latest version of a variable in derived class using pointer.

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

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

Please, No body ask me why i want to do so.I don't have any intention to do in my real code. i asked for the curiosity.

推荐答案

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

No, you cannot use virtual for fields, only for methods.

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

However you can simulate that by creating a function that returns a reference to a field:

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
}

这篇关于像,虚拟函数我们可以在 C++ 中使变量成为虚拟的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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