Qwt源码解读之QwtPoint3D类

QwtPoint3D 表征二维坐标系中的一个三维点(x, y, z)。

代码分析:

1、类接口定义:

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;
};
QwtPoint3D类是一个很简单的数据类,没有什么难点,但是如果要我们自己去定义的话,不一定能写得如作者这样完美。例如,

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++》很多人都读过,那本书里针对这个问题专门进行过讨论?求解!



 

                
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值