第二个函数给出错误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;
}
答案 0 :(得分:3)
在C ++中,如果至少有一个参数不是自定义类或者不是像enum这样的原始类,则不能重载运算符。您不能为+
类型重载int
,同样也不能为,
类型重载double
。
答案 1 :(得分:2)
将其更改为:
Sequence<double> operator,(const Sequence<double>& a, const double& b)
{
Sequence<double> seq(a);
seq.push_back(b);
return seq;
}
或(基于this article):
Sequence<double> operator,(Sequence<double> seq, const double& b)
{
seq.push_back(b);
return seq;
}