繁体   English   中英

通过调用 super 更改 class 变量

[英]Changing class variables by calling super

是否可以从 C++ 中的超级变量更改派生类的变量?

(使用一个例子可能会使我的问题更清楚..)

假设我有以下类和函数:

class SuperClass                             // super class
{            
    int myClassVariable;

public:
    virtual void modify()
    {
        myClassVariable = 10;
    }  
};

class DerivedClass  : public SuperClass     // derived class
{            
    int myClassVariable;

public:
    void modify()
    {
        super::modify();
    }  
};

如果我执行以下操作:

DerivedClass d;
d.modify();

问题:谁的myClassVariable被修改为 10? 超级class还是派生的class?

(提前感谢您的耐心和帮助..希望我的问题不是愚蠢的!)

谢谢:)

是超级class,由于超级class中修改了成员,成员不能是虚拟的,只有方法可以是虚拟的。

另请注意,在派生的 class(相对于超类)中, modify() 不是虚拟的,它仅对派生的 class 的子级是虚拟的,因为在超级 ZA2F2ED4F8EBC2CBB14C21A29DZ4 中未将 modify() 声明为虚拟。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM