我正在学习 C++。我有一个基类,Base
,及其派生类,Derived
.他们是push_back
进入std::vector<Base*> vec
.假设 vec[0] == &Base
和 vec[1] == &Derived
, 我可以为 vec[0]
切换功能和 vec[1]
没有虚函数。代码在这个问题的最后。没有虚函数有更好的方法吗?我想要纯数据类,我想添加非成员函数来修改它们以避免修改数据类的代码。非常感谢。
class TypeInterface {
public:
virtual int type(void) = 0;
virtual ~TypeInterface() {}
};
class Base : public TypeInterface {
public:
static constexpr int type_ = 1;
virtual int type(void) {
return type_;
}
virtual ~Base() {}
};
class Derived : public Base {
public:
static constexpr int type_ = 10;
virtual int type(void) {
return type_;
}
virtual ~Derived() {};
};
void Function(Base* ptr) {
std::cout << "function for Base" << std::endl;
}
void Function(Derived* ptr) {
std::cout << "function for Derived" << std::endl;
}
void SwitchFunction(int type, void* ptr) {
switch (type) {
case 1: {
Base* original_type_ptr = static_cast<Base*>(ptr);
Function(original_type_ptr);
break;
}
case 10: {
Derived* original_type_ptr = static_cast<Derived*>(ptr);
Function(original_type_ptr);
break;
}
default:
std::cout << "invalid type(=" << type << ")" << std::endl;
}
}
void test_function_selecter(void) {
Base b;
Derived d;
std::vector<Base*> vec;
vec.push_back(&b);
vec.push_back(&d);
for (auto e: vec) {
SwitchFunction(e->type(), e);
}
}
最佳答案
你不需要 'type_' 或 'int type(void)' 而是使用 'typeid'
void SwitchFunction(Base* ptr)
{
auto&& type = typeid(*ptr);
if (type == typeid(Base))
Function(dynamic_cast<Base*>(ptr));
else if (type == typeid(Derived))
Function(dynamic_cast<Derived*>(ptr));
else std::cout << "invalid type(=" << type.name() << ")" << std::endl;
}
不幸的是,这可能无法正确回答您的问题,因为它要求“Base”具有虚函数(例如析构函数,只要您的类型涉及层次结构,通常建议将其设为虚函数)
关于c++ - 在没有虚函数的情况下,有没有更好的方法来切换函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36917304/