【发布时间】:2018-10-07 12:06:01
【问题描述】:
我有一个名为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>
}
带有以下运算符的 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)
}
测试.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
这个操作可以吗?
阻止我的意思是抛出异常或警告用户不要这样做的东西。
【问题讨论】:
-
返回一个常量引用?
-
@Vivick - 我正在考虑它,但我不能,因为运算符是从其父常规 ArrayList 继承和重载的(它可以分配)。
-
@t4dohx 编辑问题并添加您的限制,这样您就不会得到不适当的答案。
-
ArrayList的部分合约支持使用operator []修改数据。如果你阻止了这一点,你就违反了 Liskov 替换原则。虽然可以在语法上执行此操作,但您不想破坏ArrayList的合同。
标签: c++ list inheritance container-data-type