c++ - 以不同方式对待子类/避免代码重复

标签 c++ c++11

我想知道如何在下面给出的场景中避免代码重复。

(有这个问题:
How do I check if an object's type is a particular subclass in C++?
答案是这是不可能的,我猜即使使用动态转换成员访问也是不可能的。)

所以我想知道您如何避免在不同的方法中使用几乎相同的代码,其中只有一个方法会有一些额外的操作。

class Basic {
    ...
}

class Advanced : public Basic {
    ...
}


AnotherClass::lengthy_method(Basic *basic) {
    // do a lot of processing, access members of basic

    if (*basic is actually of class Advanced)
        // do one or a few specific things with members of Advanced

    // more processing just using Basic

    if (*basic is actually of class Advanced)
        // do one or a few specific things with members of Advanced

    // more processing just using Basic
}


同样从设计的角度来看,AnotherClass::lengthy_method 不想在 BasicAdvanced 中定义,因为它实际上不属于它们中的任何一个.它只是对它们进行操作。

我很好奇语言专家知道什么,我希望有一个很好的解决方案,也许至少是通过 C++11 的一些功能。

最佳答案

这里可以使用dynamic_cast,只要把你要访问的Advanced成员声明为public,或者AnotherClass 被声明为 Advancedfriend:

AnotherClass::lengthy_method(Basic *basic) {
    // do a lot of processing, access members of basic

    Advanced *adv = dynamic_cast<Advanced*>(basic);
    if (adv != NULL) {
        // use adv as needed...
    }

    // more processing just using Basic

    if (adv != NULL) {
        // use adv as needed...
    }

    // more processing just using Basic
}

另一种选择是使用多态而不是 RTTI。在 Basic 中公开一些不执行任何操作的额外虚拟方法,然后让 Advanced 覆盖它们:

class Basic {
    ...
    virtual void doSomething1() {}
    virtual void doSomething2() {}
}

class Advanced : public Basic {
    ...
    virtual void doSomething1();
    virtual void doSomething2();
}

void Advanced::doSomething1() {
    ...
}

void Advanced::doSomething2() {
    ...
}    

AnotherClass::lengthy_method(Basic *basic) {
    // do a lot of processing, access members of basic

    // do one or a few specific things with members of Advanced
    basic->doSomething1();

    // more processing just using Basic

    // do one or a few specific things with members of Advanced
    basic->doSomething2();

    // more processing just using Basic
}

关于c++ - 以不同方式对待子类/避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23586838/

相关文章:

c++ - 关于在 boost.python 中将 Python 二进制文件转换为 C++ 二进制文件的错误

c++ - 如何使用 C API 创建嵌套的 Lua 表

java - 来自 Java 的 Qt Android : How to call Toast. makeText?

c++ - 在 C++ 中的什么地方使用 override 关键字

c++ - 文件何时真正写入磁盘?是否保证在 std::ofstream 被破坏后立即将文件写入磁盘?

c++ - 检索递归可变参数模板的特殊类型参数

C++ 11 线程 API : is there a free implementation for MSVC 2010?

类内的C++静态常量数组初始化

c++ - 无法在 C++ 中处理文本文件中的数据

c++ - 用户定义类的哈希函数。如何交 friend ? :)