t4d*_*ohx 0 c++ inheritance containers list
我有一个自定义结构SortedArrayList<T>,根据比较器对其元素进行排序,我想阻止使用operator[].
例:
ArrayList.h
template <typename T> class ArrayList : public List<T> {
virtual T& operator[](const int& index) override; //override List<T>
virtual const T operator[](const int& index) const override; //override List<T>
}
Run Code Online (Sandbox Code Playgroud)
SortedLinkedList.h包含以下运算符
template <typename T> class SortedArrayList : public ArrayList<T> {
public:
SortedArrayList<T>(const std::function<bool(const T&, const T&)>& comparator);
T& operator[](const int& index) override; //get reference (LHS)
const T operator[](const int& index) const override; //get copy (RHS)
}
Run Code Online (Sandbox Code Playgroud)
Test.h
ArrayList<int>* regular = new ArrayList<int>();
ArrayList<int>* sorted = new SortedArrayList<int>(cmpfn);
(*regular)[0] == 5; //allow
(*regular)[0] = 5; //allow
(*sorted)[0] == 7; //allow
(*sorted)[0] = 7; //except
Run Code Online (Sandbox Code Playgroud)
这个操作可以吗?
通过防止我的意思是抛出一个异常或什么会警告用户不要这样做.
更喜欢继承聚合:
template <typename T> class SortedArrayList {
ArrayList<T> m_the_list;
public:
SortedArrayList<T>(const std::function<bool(const T&, const T&)>& comparator);
const T& operator[](const int& index) const {return m_the_list[index];}; // always get const reference
// Can act as a *const* ArrayList<T>, but not as a mutable ArrayList<T>, as that would violate Liskov's substitution principle.
operator const ArrayList<T>&() const {return m_the_list;}
}
Run Code Online (Sandbox Code Playgroud)
正如斯蒂芬纽厄尔正确指出的那样,当你使用继承时,你保证你的班级SortedArrayList可以ArrayList在每种可能的场景中扮演一个角色.在您的示例中显然不是这种情况.
你可以在这里阅读更多关于如何违反Liskov的替代原则是一个坏主意.