您的位置:首页 > 编程语言 > C语言/C++

CPP-operator==, <overloading

2015-12-14 22:51 555 查看
如果已经定义了operator==,那么operator!=很容易实现,只要调用operator==,然后取反。

bool Array::operator!=(const Array& v) const
{
return !((*this) == v);
}


这个函数的形式实际上和具体的类无关。即如果定义了operator==,那么总能根据这个模式定义operatot!=. 同样,如果定义了<, 则很容易能够定义>. 如果定义了==,则结合<和==,则能够定义<=和>=. 标准文件util包含了一系列预先定义的这些关系操作符的模式。使用时只需定义operator==, operator<,则自动有operator!=, operator>, operator<=.因此从不需要定义多余两个比较操作符。看以下例子:为array定义<.

bool operator< (const Array& v) const;


实现:

bool Array::operator< (const Array& v) const
{
int n; //the length of the shortest of this object and v
if(num <v.num)
n = num;
else
n = v.num;
for(int i=0;i<n;i++)
if(p[i] <v.p[i])
return true;
else if(p[i]>v.p[i])
return false;
return num <v.num; //equal length
}


为了自动使用别的比较操作符。需要在类定义文件中包含以下信息:

#include〈utility>
using namespace std::rel_ops;


单操作符:operator-

Array operator- () const;

Array Array::operator- () const

{

Array temp(*this); //creat a copy of this array object

for(int i=0;i

class Myclass{
public:
bool operator== (const Myclass &vb) const {
if(this->vx == vb.vx && this->vy == vb.vy && this->vz == vb.vz) return true;
else return false;};
private:
double  vx,vy,vz;
}


其实当在一个成员函数内部写一个成员名字时候(如vx),编译器将解释为this->vx。因此以上语句其实不需要明确指出this->vx;故代码可以简化:

class Myclass{
public:
bool operator== (const Myclass &vb) const {
return(vx == vb.vx && vy == vb.vy && vz == vb.vz) };
private:
double  vx,vy,vz;
}


接下来实现矢量大小比较(长度)

bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};

inline double lengthsquare() {return(vx*vx + vy*vy + vz*vz);};


这几句总是给错误提示:

“the object has type qualifiers that are not compatible with the member function”,

因为operator< 声明为一个常函数,而函数lengthsquare()没有声明为常函数。

bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};

inline double lengthsquare() const{return(vx*vx + vy*vy + vz*vz);};


其他comparison operator:

bool operator== (const Vector3d &vb) const {return(vx == vb.vx && vy == vb.vy && vz == vb.vz);}
bool operator!= (const Vector3d &vb) const {return !(*this == vb);};
bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};
bool operator>= (const Vector3d &vb) const {return !(*this < vb);};
bool operator>  (const Vector3d &vb) const {return (*this >= vb) && (*this != vb);};
bool operator<= (const Vector3d &vb) const {return !(*this > vb);};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: