更新时间:2023-11-28 10:15:34
我猜使用 dynamic_cast
进行其他操作的真正简便方法是使用 std :: vector
而不是原始指针。
I guess the real easier way to do that other using dynamic_cast
is using std::vector
instead of a raw pointer.
示例代码
#include <string>
#include <iostream>
#include <vector>
struct Cat{
virtual ~Cat() = default;
virtual void meow() const = 0;
};
struct Meow : Cat{
void meow() const override{ std::cout << "meow" << std::endl; }
};
int main()
{
std::vector<Cat*> vec{100};
vec[1] = new Meow();
for(auto c : vec){
if(auto m = dynamic_cast<Meow*>(c)){
m->meow();
}
}
// don't forget to release memory
for(auto c : vec){
delete c;
}
}
Live Example
现代版本,使用智能
#include <string>
#include <iostream>
#include <vector>
#include <memory>
struct Cat{
virtual ~Cat() = default;
virtual void meow() const = 0;
};
struct Meow : Cat{
void meow() const override{ std::cout << "meow" << std::endl; }
};
int main()
{
std::vector<std::unique_ptr<Cat>> vec{100};
vec[1] = std::make_unique<Meow>();
for(auto&& c : vec){
if(auto m = dynamic_cast<Meow*>(c.get())){
m->meow();
}
}
// you don't need to manually clear the memory.
}
Live Example