QwtPoint3D 表征二维坐标系中的一个三维点(x, y, z)。
代码分析:
1、类接口定义:
QwtPoint3D类是一个很简单的数据类,没有什么难点,但是如果要我们自己去定义的话,不一定能写得如作者这样完美。例如,class QWT_EXPORT QwtPoint3D { public: QwtPoint3D(); // 默认构造函数 QwtPoint3D( double x, double y, double z ); // 三个参数的构造函数 QwtPoint3D( const QwtPoint3D & ); // 拷贝构造函数,为什么要自定义? 难道编译器提供的默认拷贝构造函数不能满足需要吗?求解! QwtPoint3D( const QPointF & ); // 由一个二维点构造一个三维点,其实相当于一个转换函数 bool isNull() const; // 是否为空点,见其定义 double x() const; double y() const; double z() const; double &rx(); double &ry(); double &rz(); void setX( double x ); void setY( double y ); void setZ( double y ); QPointF toPoint() const; bool operator==( const QwtPoint3D & ) const; bool operator!=( const QwtPoint3D & ) const; private: double d_x; double d_y; double d_z; };
1) 提供了 isNull() 接口。
/*! Returns true if the point is null; otherwise returns false. A point is considered to be null if x, y and z-coordinates are equal to zero. */ inline bool QwtPoint3D::isNull() const { return d_x == 0.0 && d_y == 0.0 && d_z == 0; }
2) 接口全部实现为内联函数,从而保证了效率优化。
3) 提供了访问成员变量引用的接口:
double &rx();
double &ry();
double &rz();
当然, 不知道作者提供这组接口的用意何在?因为QwtPoint3D类中的成员变量都为基本数据类型,这样设计无益于效率优化。
通常情况下,就我个人观点,不推荐使用这组接口,应该使用
double x() const;
double y() const;
double z() const;
代替。
4) 提供了转换函数 QPointF toPoint() const; 与构造函数 QwtPoint3D( const QPointF &other ); 形成对应的反向转换功能。
5) 重载了==(等于)和 != (不等于)操作符:
//! Returns true if this point and other are equal; otherwise returns false. inline bool QwtPoint3D::operator==( const QwtPoint3D &other ) const { return ( d_x == other.d_x ) && ( d_y == other.d_y ) && ( d_z == other.d_z ); } //! Returns true if this rect and other are different; otherwise returns false. inline bool QwtPoint3D::operator!=( const QwtPoint3D &other ) const { return !operator==( other ); }
“不等于”操作符通常用“等于”操作符来实现,当然,反之亦可。
不过,这里(包括1)有一点疑问,就是关于浮点数的比较?
return d_x == 0.0 && d_y == 0.0 && d_z == 0;和
return ( d_x == other.d_x ) && ( d_y == other.d_y ) && ( d_z == other.d_z );这里直接对两个双精度浮点数进行相等比较。
相信林锐博士的《高质量程序设计指南——C/C++》很多人都读过,那本书里针对这个问题专门进行过讨论?求解!