在运行时没有虚函数的基类方法中访问派生类方法

时间:2011-04-14 17:53:42

标签: c++ oop

我有以下代码示例。一个基类和两个派生类,每个类都有自己的函数(分别是function1和function2)。 function1和function2都不是基类中的虚拟。我无法改变这一点,因为这些类已经实现。

#include <iostream>    
class Base
{
public:
    Base(){}
    Base(int val) : m_base(val){}
    virtual ~Base(){}
    //base class methods
private:
    int m_base;
};

class Derived1 : public Base
{
public:
    Derived1(int val) : m_derived1(val){}
    ~Derived1(){}
    void print1(){std::cout << "Using Derived 1 class method" << std::endl;};
private:
    int m_derived1;
};

class Derived2 : public Base
{
public:
    Derived2(int val) : m_derived2(val){}
    ~Derived2(){}
    void print2(){std::cout << "Using Derived 2 class method" << std::endl;};
private:
    int m_derived2;
};

我正在努力实现以下目标。我想决定我想要使用的派生类的运行时间。 此外,我想通过仅使用对象b从基类方法中调用它们。否则我将不得不为我允许在运行时输入的每个选项重写我的程序(实际上我有一些我可以选择的类)。

int main()
{
    int option;
    std::cin >> option;

Base* b = new Base(5);

Derived1* d1 = new Derived1(5);
Derived2* d2 = new Derived2(5);

d1->print1(); //obviously this works
d2->print2(); //obviously this works

//In reality I thus have a function in d1 and d2 which is not present in b
//I have to decide on runtime which class I need to use

if(option == 1)
{
    b = d1;
}
else if(option == 2)
{
    b = d2;
}

/*
Rest of program ...
    b->invokeMethod;
    // ... //
    b->invokeMoreMethods;
*/

//Call derived functions on base object

//b->print1(); //fails obviously
if(option == 1)
{
    dynamic_cast<Derived1*>(b)->print1(); //will work if option == 1 is specified (*)
}
if(option == 2)
{
    dynamic_cast<Derived2*>(b)->print2(); //will work if option == 2 is specified (*)
}

return 0;
}

是否可以在没有if(选项== 1)和if(选项== 2)循环的情况下执行(*)代码行?我无法使用任何虚拟功能,因为它没有实现......这个问题是否有更优雅的解决方案?

1 个答案:

答案 0 :(得分:1)

你可能会编写一个用指针初始化的包装器,并在一天结束时在内部解析动态调度,但我不确定这是值得的。如果你可以修改这三种类型,那就是你应该做的目标,其他一切都只是一个讨厌的黑客。

使用std :: / boost :: function进行Hack:

int main() {
    Base * b = 0;                    // You were leaking a Base object here
    boost::function< void () > f;
    ...
    if ( option == 1 ) {
       Derived1 d1 = new Derived1;   // Only instantiate the object you will use
       b = d1;
       f = boost::bind( &Derived1::print1, d1 );
    } else if ( option == 2 ) {
       Derived2 d2 = new Derived2;
       b = d2;
       f = boost::bind( &Derived2::print2, d2 );
    }
    ...
    f(); // will call either d1->print1(), or d2->print2()
    ...
    delete b;                      // should really use a smart pointer but I left
                                   // the raw pointer to minimize changes
}

请注意,这是一个令人讨厌的伎俩,而且很难很容易维护。