簡體   English   中英

就像虛函數一樣,我們可以在C ++中使變量虛擬嗎

[英]Like, virtual function can we make a variable virtual in c++

當基類指針指向其派生類的對象時,並且如果某個函數被重寫,我們將使用虛擬函數來解決該問題。 這樣我們就可以使用指針訪問派生類的自身功能。 像這樣,我在想,如果有一種方法可以應用於variable中的virtual關鍵字,以便我們可以使用指針訪問派生類中變量的最新版本。

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

您不能使用virtual關鍵字覆蓋成員變量。 但是,您可以在基類和派生類中使用virtual getter和setter引用不同的成員變量,以實現類似的效果:

class base {
public:
    virtual int getX() {
        return x;
    }
    virtual void setX(int x) {
        this->x = x;
    }
private:
    int x;
}

class derived : public base {
public:
    int getX() {
        return x;
    }
    void setX(int x) {
        this->x = x;
    }
private:
    int x;
}

其他答案完全可以,但您也可以使用更簡單的語法:

class base {
public:
    virtual operator int&() { return x; };
    virtual operator int() { return x; };
protected:
    int x;
};

如果您要在類中虛擬化單個變量。

第二個聲明只是避免在只需要值時使用引用,而在分配引用時會自動為您選擇。

您可以從base派生的類中隨意重寫這些運算符。

class derived : public base {
    public:
    operator int() override { return x * 5; };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM