我有几个类共享一个公共基类,只是它们的方法工作方式不同。所以在下面的例子中,加法器和乘法器是相同的,只是它们的计算方式不同。
有没有办法即时将“a”更改为乘数?我是否需要实现将派生类相互转换的方法?例如类似的东西
a = a.asMultiplier()
?
正如您在下面的代码中看到的那样,我尝试将 reinterpret_cast 转换为乘数,但没有成功,它仍然像加法器一样工作。(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;
}