在C++中在运行时在用户定义的类之间进行更改

Pau*_*aul 1 c++ pointers casting user-defined-types

我有两个类,一个扩展另一个.他们都有一个叫做doSomething()执行不同的方法.我希望能够有一个我可以切换class A到的指针,class B并让其余的代码运行相同,因为它们每个都有相同的方法名称.这是可能的,这是正确的方法吗?另外,我对C++很陌生,所以它可能只是一个问题.

class A {
    void doSomething()
    {
        // does something
    }
};

class B: public A {
    void doSomething()
    {
        //does something else
    }
};


main()
{
    A *ptr = new A;
    B *bptr = new B;

    // a giant loop

    ptr->doSomething();


    if(condition) 
    {
        ptr = bptr;
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*had 5

我可以想到两种方法来实现这一目标.

如果你已经有多态类型,你的方式很好(有一些小的改动).(如果BA-an,逻辑上)

class A
{
public:
    virtual void f() { /* something */ };
};

class B : public A
{
public:
   virtual void f() { /* something else */ };
};

int main()
{
   A a;
   B b;
   A* c = 0;

   // based on your condition
   c = &a;
   c->f();
   c = &b;
   c->f();

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你的类型不是那么密切相关呢?使用继承意味着类之间的关系非常严格(在这种情况下是is-a).是B真正的A

这是为具有相同命名功能的类实现此目的的一种方法,但实际上并不是类似的类型.

template <class T>
void do_f(T& obj)
{
   obj.f();
}

class D
{
public:
   void f() { /* something */ }
};

class E
{
public:
   void f() { /* something else entirely */ }
};

int main()
{
   // note, D and E have no relation
   D d;
   E e;

   // based on your condition
   do_f(d);
   do_f(e);
}
Run Code Online (Sandbox Code Playgroud)