[英]Overloading class' operator [] in C++
我有一個類,我編寫了它的[]運算符,我希望有時運算符將返回一個int ,有時返回一個結構 。
但是編譯器不會讓我重載運算符,為什么呢?
它說:“......不能超載”
碼:
template <class T> struct part
{ };
template <class T> class LinkedList
{
public:
LinkedList() : size(0), head(0) {}
T& operator[](const int &loc);
part<T>& operator[](const int &loc);
};
template <class T> T& LinkedList<T>::operator[](const int &loc)
{
..a lot of thing which compiles perfectly
}
template <class T> part<T>& LinkedList<T>::operator[](const int &loc)
{
...the same thing but returns struct&.
}
您不能基於返回類型重載函數。 您可以讓您的運算符返回int和string的變體,並讓用戶檢查實際返回的內容,但是它很麻煩。 如果可以在編譯時確定返回類型,則可以通過具有不同的索引類型來實現運算符重載。 像這樣的東西:
struct as_string
{
as_string( std::size_t index ) : _index( index ){}
std::size_t const _index;
};
...
int operator[]( int index ) const { ... };
std::string operator[]( as_string const& index ) const { ... };
然后調用者將調用object[0]
來獲取int
結果,或object[as_string(0)]
來獲取string
結果。
函數輸出的類型不是函數簽名的一部分。 因此,您不能同時使用int operator[](int index)
和Foo operator[](int index)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.