操作符重载应该设计成类成员函数还是普通非成员函数?

来源:互联网 发布:java程序员成长之路 编辑:程序博客网 时间:2024/05/02 00:54

四小点:


1.=,[ ],( ),->这四个操作符重载必须定义为类成员函数。


2.复合赋值操作符重载通常应定义为类成员函数。复合赋值操作符如*=,+=等。但是不一定得这么做。


3.改变对象状态或者与给定对象联系紧密的操作符,如++,---,*等,通常定义为类成员函数。


4.对称操作符,如算术,相等,关系,位操作符,最好定义成普通非成员函数。


下面是自己N年之前写过的一个3D类:

#include <iostream>using namespace std;class Vector3{public:double x,y,z;public:Vector3(double nx = 0.0,double ny = 0.0,double nz = 0.0):x(nx),y(ny),z(nz){}Vector3(const Vector3 &rhs){operator = (rhs);}Vector3& operator =(const Vector3 &rhs){if(this != &rhs){x = rhs.x;y = rhs.y;z = rhs.z;}return *this;}void zero(){x = 0.0;y = 0.0;z = 0.0;}Vector3 operator - () const{return Vector3(-x,-y,-z);}Vector3& operator += (const Vector3 &rhs){x += rhs.x;y += rhs.y;z += rhs.z;return *this;}Vector3& operator -= (const Vector3 &rhs){x -= rhs.x;y -= rhs.y;z -= rhs.z;return *this;}Vector3& operator *= (double a){x *= a;y *= a;z *= a;return *this;}Vector3& operator /= (double a){double oneOverA = 1 /a; x *= oneOverA;y *= oneOverA;z *= oneOverA;return *this;}void normalize()  //标准化{double Mag  = sqrt(x * x + y * y + z * z);if(Mag > 0.0){double oneOverMag = 1.0 / Mag;x *= oneOverMag;y *= oneOverMag;z *= oneOverMag;}}void print() const{cout << x << " " << y << " " << z << endl;}};bool operator ==(const Vector3 &lhs, const Vector3 &rhs){return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z ==rhs.z;}bool operator !=(const Vector3 &lhs, const Vector3 &rhs){return !(lhs == rhs);}Vector3 operator + (const Vector3 &lhs, const Vector3 &rhs){Vector3 temp(lhs);temp += rhs;return temp;}Vector3 operator - (const Vector3 &lhs, const Vector3 &rhs){Vector3 temp(lhs);temp -= rhs;return temp;}Vector3 operator * (const Vector3 &lhs, double a)  //标量右乘{Vector3 temp(lhs);temp *= a;return temp;}Vector3 operator * (double a,const Vector3 &rhs)  //标量左乘{Vector3 temp(rhs);temp *= a;return temp;}Vector3 operator * (const Vector3 &lhs, const Vector3 &rhs)  //点乘{return Vector3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z);}Vector3 crossProduce(const Vector3 &lhs, const Vector3 &rhs) //叉乘{return Vector3(lhs.y * rhs.z - lhs.z * rhs.y,lhs.z * rhs.x - lhs.x * rhs.z,lhs.x * rhs.y - lhs.y * rhs.x);}double vectorMag(const Vector3 &a)  //求模{return sqrt(a.x * a.x + a.y* a.y + a.z * a.z);}double Distance(const Vector3 &lhs, const Vector3 &rhs) //求距离{Vector3 temp = rhs - lhs;return vectorMag(temp);}int main(){Vector3 a(1,2,3);Vector3 b(1,1,1);Vector3 c = a * 3;c.print();Vector3 d = 3 * a;d.print();Vector3 e = -a;e.print();return 0;}


0 0
原创粉丝点击