重载类' C++ 中的运算符 []
我有一个类,我编写了它的 [] 运算符,我希望该运算符有时返回一个 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&.
}
I have a class which I have written its [] operator, and I want that sometimes the operator will return an int and sometimes a struct.
But the compiler won't let me overload the operator, why?
It says:"...cannot be overloaded"
Code:
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&.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能根据返回类型重载函数。您可以让运算符返回 int 和 string 的变体,并让用户检查实际返回的内容,但这很麻烦。如果可以在编译时确定返回类型,则可以通过具有不同的索引类型来实现运算符重载。像这样的事情:
然后调用者将调用
object[0]
来获取int
结果,或者调用object[as_string(0)]
来获取获取字符串
结果。You can't overload a function based on the return type. You could have your operator return a variant of int and string, and let the user check which was actually returned, but its cumbersome. If the return type can be determined at compilation time, you can implement the operator overloads by mean of having different indices types. Something like this:
And then the caller would invoke
object[0]
to get anint
result, orobject[as_string(0)]
to get astring
result.函数输出的类型不是函数签名的一部分。因此,您不能同时使用
intoperator[](intindex)
和Foooperator[](intindex)
。The type of a function's output is not a part of the function's signature. Thus you can't use both
int operator[](int index)
andFoo operator[](int index)
.