c++ 改变超类行为的函数

问题描述 投票:0回答:0

我有一个被子类化的工具。报告了一个错误,其中子类从它不应该拥有的超类中获取了一个值。

mySuperclass.SetMyVar()
正在为子类调用

如果我做不到

SetMyVar
private
- 因为它在两个类发生的初始化中被调用 - 我可以使行为取决于这是超类项目还是子类项目?

建议的修复 - 为子类提供

SetMyVar()
- 如果再次派生超类,则会出现维护问题。

[不过,如果我使用了

b.SetMyVar()
但它没有这样做,那么我可能还有另一个 bug 需要解决......也许子类实现是正确的]

像这样

class A
{
public:
    A() {myVar = 20; }

    void SetMyVar(int val)
    {
        //eg (typeid (this).name() == "class A*") // doesn't work
        //eg (dynamic_cast <A*>(this)) // doesn't work

[something here to make it happen for only objects of type superclass]
        {
            myVar = val;
        }
    }

    int myVar;
};


class B : public A
{
public:
    B() { myVar = 10; }
};

int main(...)
{
    A a;
    B b;

    a.SetMyVar(2);
    b.SetMyVar(3); < -- this should not set myVar 

    std::cout << a.myVar << " : " << b.myVar;

    return 0;
}
c++ superclass
© www.soinside.com 2019 - 2024. All rights reserved.