【发布时间】:2018-04-17 15:12:44
【问题描述】:
我有两个类A 和B,它们派生自同一个基类Base。
我主要定义了一个向量Base *,我用它来存储A和B的元素。
使用 reinterpret_cast 我可以调用他们真实类的方法。
这段代码安全吗?有没有更好/标准的方法来做到这一点?
实际代码中的两个类共享基类的大部分方法,但A 拥有一些与Base 或B 不共享的方法,B 也是如此,因此 virtual 不是选项。
#include <iostream>
#include <vector>
class Base {
};
class A : public Base {
public:
void print_from_A() {
std::cout << "hello from A\n";
}
};
class B : public Base {
public:
int number;
void read_from_B() {
std::cin >> number;
}
};
int main(int argc, char * argv[]) {
std::vector<Base*> v;
v.push_back(new A());
v.push_back(new B());
(reinterpret_cast<A *>(v[0]))->print_from_A();
(reinterpret_cast<B *>(v[1]))->read_from_B();
for(auto && e: v) {
delete e;
}
return 0;
}
编辑:
似乎使用reinterpret_cast 是未定义的行为:Casting to one class and calling function from sibling class?
似乎正确的方法是使用static_cast:Can I get polymorphic behavior without using virtual functions?
这是答案吗?
【问题讨论】:
-
给
Base添加一个虚析构函数,使用dynamic_cast做向下转换,尽量不要向下转换。
标签: c++ polymorphism