c++ - 我应该使用函数指针还是多态?

标签 c++ polymorphism function-pointers

我需要将对象传递给类,并根据传递的对象中的值,让类使用两组方法中的一种。在这门课上我不会以任何方式改变 b 。我希望这对用户尽可能透明,以便他们传入对象,然后像往常一样调用方法,所以我试图避免单独管理 Foo1 和 Foo2 类的需要。

例如

class Foo
{
    public:
        Foo(Bar & b){
            useScheme1 = b.a == 1;
        }

        void methodA(){
            // call either A1 or A2
        }

        void methodB(){
            // call either B1 or B2
        }

    protected:
        bool useScheme1 = false;
        // methods A1, A2, B1 and B2 defined as protected functions
        .
        .
        .

};

最佳答案

这种功能正是动态多态性的用途!我绝对会建议使用一个非常基本的创建者函数和 Foo + children,像这样:

namespace foo_library {

class Foo
{
public:
    virtual void methodA() = 0;

    virtual void methodB() = 0;

    virtual ~Foo() {}
};

class Foo1 : public Foo
{
    virtual void methodA()
    {
        // Do A1 here.
    }

    virtual void methodB()
    {
        // Do B1 here.
    }
};

class Foo2 : public Foo
{
    virtual void methodA()
    {
        // Do A2 here.
    }

    virtual void methodB()
    {
        // Do B2 here.
    }
};

Foo* create_foo(const Bar& b)
{
    if(b.a == 1) return new Foo1;

    return new Foo2;
}
}

// Then you use it like this:
int main()
{
    Bar b; // Initialize it.
    std::unique_ptr<foo_library::Foo> foo = foo_library::create_foo(b);    // Use the appropriate smart pointer for your ownership needs.
    foo->MethodA();   // Decides which to do based on the bar.
}

关于c++ - 我应该使用函数指针还是多态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872406/

相关文章:

c++ - 在 QTableWidget 中嵌入 QComboBox 时遇到问题

c++ - AdjustTokenPrivileges 错误 ERROR_NOT_ALL_ASSIGNED

C++如何扩展一个类并转换为具有相同名称的适当类型

c - 函数指针C语言编程

Javascript:将函数指针放入对象中?

c++ - 传递给模板函数时,lambda 自动衰减为函数指针

c++ - 替代宏以帮助类型安全和减少重复

c++ - 参数传递机制?

c++ - 如何通过映射从派生类实例化对象

C++ 多态性和类型转换