我從Base類繼承來創建兩個不同的派生類(Derived1和Derived2),然後將它們放入一個向量中。假設我想根據類的類型調用派生類的函數。如何從包含基類指針的容器調用派生類函數(基於它的類型)?
僞代碼:
if holder[1] stored Derived1 then I want to call GetZ()
else if holder[1] stored Derived2 then I want to GetFlag().
嘗試:
#include <iostream>
#include <memory>
#include <vector>
class Base {
public:
Base(int x, int y) : x_(x), y_(y) {}
int GetX() { return x_; }
int GetY() { return y_; }
private:
int x_;
int y_;
};
class Derived1 : public Base {
public:
Derived1(int x, int y, int z) : Base(x, y), z_(z) {}
int GetZ() { return z_; }
private:
int z_;
};
class Derived2 : public Base {
public:
Derived2(int x, int y, bool flag) : Base(x, y), flag_(flag) {}
bool GetFlag() { return flag_; }
private:
bool flag_;
};
std::vector<std::shared_ptr<Base>> holder;
void print();
int main() {
holder.push_back(std::make_shared<Derived1>(3, 4, 5));
holder.push_back(std::make_shared<Derived2>(6, 7, true));
print();
}
void print(){
for(auto& it : holder){
// call this if "it" is Derived2
// else call it->GetX()
// currently this gives compilation error
// because of object slicing
std::cout << it->GetFlag() << std::endl;
}
}
如果你不能以一種他們提供類似接口的方式編寫你的類,那麼多態可能不是最好的方法。 – patatahooligan
另一種可能性是訪客模式。 – Jarod42