将对象从一个派生类更改为另一个派生类 [英] Changing an object from one derived class to another

查看:135
本文介绍了将对象从一个派生类更改为另一个派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类共享一个公共的基类,除了它们的方法工作方式不同。因此,在下面的例子中,除了执行计算的方式外,Adder和Multiplier是相同的。

I have a couple of classes that share a common base class, with the exception that they differ in the way their methods work. So in the example below, Adder and Multiplier are the same except for the way in which their calculation is performed.

有一种方法可以将a在飞行?我需要实现将派生类彼此转换的方法吗?例如例如

Is there a way to change "a" to a Multiplier on the fly? Do I need to implement methods which convert derived classes to each other? e.g. something like

a = a.asMultiplier()

正如你在下面的代码中看到的,我试过reinterpret_cast到一个乘数,没有运气,它仍然像一个加法器。 (gcc OS X v4.2.1)

As you can see in the code below I tried reinterpret_cast to a Multiplier, with no luck, it still acts like an Adder. (gcc OS X v4.2.1)

#include <iostream>


class Base {
protected:
    int a,b;    
public:
    Base(int a, int b) {
        this->a = a;
        this->b = b;
    }  
    virtual ~Base() { }    
    virtual int calculate() = 0;
};


class Adder : public Base {    
public:
    Adder(int a, int b) : Base(a, b) {

    }      
    int calculate() {
        return this->a + this->b;
    }
};


class Multiplier : public Base {    
public:
    Multiplier(int a, int b) : Base(a, b) {    
    }  

    int calculate() {
        return this->a * this->b;
    }
};



int main() {

    Base* a = new Adder(3,4);
    Base* m = new Multiplier(3,4);

    std::cout << "Adder gives " << a->calculate() << std::endl;
    std::cout << "Multiplier gives " << m->calculate() << std::endl;

    a = reinterpret_cast<Multiplier*>(a);

    std::cout << "Now adder gives " << a->calculate() << std::endl;

    delete a;
    delete m;
    return 0;
}


推荐答案

给我解决这个问题,是实现一个复制构造函数,取基础类:

The best thing that comes up to me to solve this, is implementing a copy constructor, taking the base class:

class Multiplier : public Base {    
public:
    Multiplier(int a, int b) : Base(a, b) {    
    }  

    explicit Multiplier(const Base& iBase) : Base(iBase.a, iBase.b) {    
    }  

    int calculate() {
        return this->a * this->b;
    }
};

但是因为我不是这里最先进的c ++开发人员,所以可能不正确,有一个更好的主意,只是试图:)

But since I am not the most advanced c++ developer here, it might not be correct or other people might have a better idea, just trying :)

这篇关于将对象从一个派生类更改为另一个派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆