C++ 向std::vector添加运算符<;T>;
我试图在std::vector中添加一个操作符,以确定两个向量何时大致相同。我该怎么做C++ 向std::vector添加运算符<;T>;,c++,operators,C++,Operators,我试图在std::vector中添加一个操作符,以确定两个向量何时大致相同。我该怎么做 template<typename T> //only numeric types class ImperciseVector: public std::vector<T> { public: ImperciseVector() {} //is this constructor needed? bool operator~ (const Impe
template<typename T> //only numeric types
class ImperciseVector: public std::vector<T> {
public:
ImperciseVector() {} //is this constructor needed?
bool operator~ (const ImperciseVector& v) {
T l1sq=0.0, l2sq=0.0, l3sq=0.0;
if ((*this).size() != v.size() || (*this).size==0 || v.size()==0) return false;
for (int j = 0; j<(*this).size(); j++) {
l1sq += (*this)[j]*(*this)[j];
l2sq += v[j]*v[j];
l3sq+= ((*this)[j]-v[j])*((*this)[j]-v[j]);
}
//some estimate such that length of their their difference (relative to their size) is small enough
if (l3sq/(l1sq*l2sq) <= 0.00001) return true;
return false;
}
};
template//仅限数字类型
类不精确向量:public std::vector{
公众:
不精确向量(){}//是否需要此构造函数?
布尔算子(常数不精确向量&v){
T l1sq=0.0,l2sq=0.0,l3sq=0.0;
如果(*this.size()!=v.size()| |(*this.size==0 | | v.size()==0)返回false;
for(int j=0;joperator~()
是一元运算符。它的用法只能是~iv
,不能是iv1~iv2
。在这种情况下,最好只编写一个名为approx()
或重载operator=
的成员函数(这是有意义的,对吧?如果两个不精确向量
s近似相等,那么它们是相等的?)
旁注,不要让不精确向量
继承自向量
。改用组合。哦,这是有道理的。现在我想运算符==的重载实际上起作用了,我有点犹豫,因为它们似乎都采用相同的参数类型(这不是真的)同样数量的参数,所以它看起来模棱两可。你是说用合成来代替吗?比如类不精确向量{class std::vector;bool操作符==(…){…}?@Fr4ns是的,这就是合成。