C++覆盖全局运算符逗号会出现错误
第二个函数给出错误 C2803 http://msdn. microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx:“operator”必须至少有一个类类型的形参。有什么线索吗?
template<class T,class A = std::allocator<T>>
class Sequence : public std::vector<T,A> {
public:
Sequence<T,A>& operator,(const T& a) {
this->push_back(a);
return *this;
}
Sequence<T,A>& operator,(const Sequence<T,A>& a) {
for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) {
this->push_back(a.at(i));
}
return *this;
}
};
//this works!
template<typename T>
Sequence<T> operator,(const T& a, const T&b) {
Sequence<T> seq;
seq.push_back(a);
seq.push_back(b);
return seq;
}
//this gives error C2803!
Sequence<double> operator,(const double& a, const double& b) {
Sequence<double> seq;
seq.push_back(a);
seq.push_back(b);
return seq;
}
the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue?
template<class T,class A = std::allocator<T>>
class Sequence : public std::vector<T,A> {
public:
Sequence<T,A>& operator,(const T& a) {
this->push_back(a);
return *this;
}
Sequence<T,A>& operator,(const Sequence<T,A>& a) {
for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) {
this->push_back(a.at(i));
}
return *this;
}
};
//this works!
template<typename T>
Sequence<T> operator,(const T& a, const T&b) {
Sequence<T> seq;
seq.push_back(a);
seq.push_back(b);
return seq;
}
//this gives error C2803!
Sequence<double> operator,(const double& a, const double& b) {
Sequence<double> seq;
seq.push_back(a);
seq.push_back(b);
return seq;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++ 中,如果运算符的至少一个参数不是自定义类或非像枚举这样的原始类型,则不能重载运算符。您不能为
int
类型重载+
,同样,您也不能为double
类型重载,
。In C++ you can't overload operator if at least one of the parameters of it is not a custom made class or something not primitive like enum. You can't overload
+
forint
types and similarly you can't overload,
fordouble
types.将其更改为:
或(基于这篇文章< /a>):
Change that to:
or (based on this article):