我有一个类,我已经编写了它的 [] 运算符,我希望运算符有时返回一个 int,有时返回一个 struct。
但是编译器不允许我重载运算符,为什么?
它说:“...不能重载”
代码:
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&.
}
最佳答案
您不能根据返回类型重载函数。您可以让您的运算符(operator)返回一个 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
结果。
关于c++ - 在 C++ 中重载类的运算符 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705492/