C++ 在派生类和基类中使用同名的两个变量

标签 c++ class inheritance casting polymorphism

我之前已经发布过这个问题 ( Here ),这是一种不同的解决方案。这个解决方案似乎更好地封装了那些实现类的行为,因为它阻止了他们需要显式向上转换。

问题是:

我有一个项目,我想在其中隔离大多数对象的核心行为,同时通过派生对象提供额外的行为。足够简单:

class BaseA
{
    virtual void something() {}
}


class DerivedA : public BaseA
{
    void something() {}
    void somethingElse() {}
}

现在假设我还有第二组类,相同的继承方案,只是它们聚合了上述类。但是,我希望基版本使用基类,而派生版本在派生类中。我的解决方案是考虑使用相同的名称“隐藏”基类变量;

class BaseB
{
    BaseA *var;

    BaseB()
    {
        var = new BaseA();
    }

    virtual void anotherThing1();
    virtual void anotherThing2();
    virtual void anotherThing3();
}

class DerivedB : public BaseB
{
    DerivedA *var;

    DerivedB()
    {
        var = new DerivedA();
    }

    void anotherThing1();
    void anotherThing2();
    void anotherThing3();
    void andAnother1();
    void andAnother2();
}

这种方法的目标是使依赖派生聚合类的函数不再需要显式转换来实现获得的功能。

void func1( BaseB &b )
{
    b.anotherThing1();
    b.var->something();
}

void func2( DerivedB &b )
{
    b.anotherThing1();
    b.andAnother1();
    b.var->something();
    b.var->somethingElse();
}

void main( int argc, char **argv )
{
    BaseB    baseB;
    DerivedB derivedB;

    func1( baseB );
    func1( derivedB );
    func2( derivedB );
}

这会被视为不好的做法吗?

最佳答案

Would this be considered bad practice?

是的,这是一种不好的做法,因为 Base 中的 var 将不会被使用。它看起来不像 DerivedB 应该派生自 BaseB:相反,它们应该派生自相同的抽象基类,如下所示:

class AbstractB {
public:
    virtual void anotherThing1() = 0;
    virtual void anotherThing2() = 0;
    virtual void anotherThing3() = 0;
};
class DerivedB1 : public AbstractB { // Former BaseB
    BaseA *var;

public:
    DerivedB1() {
        var = new BaseA();
    }
    virtual void anotherThing1();
    virtual void anotherThing2();
    virtual void anotherThing3();
};
class DerivedB2 : public AbstractB { // Former DerivedB
    DerivedA *var;
public:
    DerivedB2() {
        var = new DerivedA();
    }
    void anotherThing1();
    void anotherThing2();
    void anotherThing3();
    void andAnother1();
    void andAnother2();
};

这里使用的一般原则是您应该尝试使继承层次结构中的所有非叶类抽象。

关于C++ 在派生类和基类中使用同名的两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552336/

相关文章:

c++ - 在编译时逐步构建变量指针的 vector

ios - 这个方法的定义有什么问题? ( objective-C )

java - 将 Java 对象/字符串转换为实际类

c++ - Win32 API 中 PathAppend 和 PathCombine 的区别

c++ - 可以在 Windows 上创建受密码保护的 zip 文件的 C zip 库?

c++ - gcc 是否对 VLA 的 sizeof 运算符进行了不同的评估?

r - 在 R 中使用 apply 时丢失类信息

java - 即使在Java中初始化子类后,静态变量的值也不会改变

c++ - 查找基类/父类(super class)成员的实现

C++、虚继承、奇怪的抽象类+克隆问题