我正在學習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);
}
}
你的代碼有未定義的行爲。那些是一些討厭的演員。理想情況下,當你剛剛學習C++時,你根本不應該使用指針或轉換... –
如何將函數存儲爲變量?如果它用於所有實例,則可以將其設置爲靜態。 std :: function myFunc = [](void){// do something} –
Striker
謝謝你,Kerrek SB。我試圖找到你的擔心,我想你可能會擔心我可能會使用錯誤的類型和void *組合。在我的情況下,SwitchFunction(e-> type(),e)具有固定格式。所以我希望我可以避免選錯組合。 – mora