c++ - 比如,虚函数我们可以在 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;
}
拜托,没有人问我为什么要这样做。我没有任何打算在我的真实代码中这样做。我问他的好奇心。
解决方案
不,您不能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
}
推荐阅读
- asp.net-core - 核心中的两个模型
- swift - 委托函数中的数组为空
- minify - 如何将 terser 选项传递给 html-minifier-terser
- reactjs - 反应钩子如何组合数组
- python - 在末尾识别连续的非 nan 值
- javascript - 关于如何通过 HTTP 传输图像并在 JavaScript 中处理图像的困惑
- mediawiki - Debian buster 上 pdf 失败的 PdfHandler 预览图像
- google-cloud-vision - AutoML 单图像分类预测返回“无对象”
- javascript - JQuery DirtyForms 和 Bootstrap 导航选项卡
- javascript - React.js - 从 POST 方法获取响应