Ada*_*nst 8 c++ polymorphism abstract-class stl map
我有这样的类层次结构:
struct Vehicle {
virtual string model() = 0; // abstract
...
}
struct Car : public Vehicle {...}
struct Truck : public Vehicle {...}
Run Code Online (Sandbox Code Playgroud)
我需要保留std::map一些关于某些Vehicle实例的信息:
std::map<Vehicle, double> prices;
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
/usr/include/c++/4.2.1/bits/stl_pair.h: In instantiation of ‘std::pair<const Vehicle, double>’:
/usr/include/c++/4.2.1/bits/stl_map.h:349: instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = Vehicle, _Tp = double, _Compare = std::less<Vehicle>, _Alloc = std::allocator<std::pair<const Vehicle, double> >]’
test.cpp:10: instantiated from here
/usr/include/c++/4.2.1/bits/stl_pair.h:73: error: cannot declare field ‘std::pair<const Vehicle, double>::first’ to be of abstract type ‘const Vehicle’
Model.hpp:28: note: because the following virtual functions are pure within ‘const Vehicle’:
Model.hpp:32: note: virtual string Vehicle::model()
Run Code Online (Sandbox Code Playgroud)
因此,您不能使用抽象类作为std::map键.据我所知,这是因为map复制了它们的键(通过copy-constructor或赋值运算符),这意味着实例化一个抽象类(Vehicle).即使你可以,我们也会成为对象切片的牺牲品.
我该怎么办?
似乎我不能使用指针,因为可能存在逻辑上相同的Cars或Trucks的单独副本 .(即两个Car对象分别实例化,但代表同一辆汽车并operator==返回true.我需要这些对象映射到相同的对象std::map.)
Beg*_*oth 10
你需要使用指针Vehicle.
operator==不是由std::map比较函子使用的,而比较函子是第三个参数std::map.默认情况下是std::less.您需要实现自己的比较仿函数才能使用Vehicle:
struct less_vehicle: std::binary_function<const Vehicle *, const Vehicle *, bool>
{
bool operator() (const Vehicle *a, const Vehicle *b) const { ... }
};
Run Code Online (Sandbox Code Playgroud)然后使用它:
std::map<Vehicle *, double, less_vehicle>
Run Code Online (Sandbox Code Playgroud)