注册 登录
编程论坛 C++教室

测试面向对象编程的相关机制

bo_rui 发布于 2021-05-23 07:36, 1040 次点击
测试面向对象编程的相关机制:
通过类模版定义点,每个点有x、y两个座标,通过构造函数建立对象,重载>>运算符使这个点向右移动(x座标增加)。
1 回复
#2
rjsp2021-05-23 10:20
惜字如金呀,但问题是你将问题描述清楚了吗?!
    试面向对象编程的相关机制 --- 楞没看出后面的描述与“面向对象”有一丝一毫的关系。既然惜字如金的话,这一句可以“惜”掉;
    通过类模版定义点 --- 通过类模版定义“点”
    通过构造函数建立对象 --- ???
    重载>>运算符使这个点向右移动 --- 懒得吐槽了。是不是如下所示,定义为成员模板函数,还是仅成员函数? 是不是如下所示,返回point类型的临时对象,还是返回point&类型的*this?

程序代码:
#include <utility>

template<typename T>
struct point
{
    explicit point( T x_=T(), T y_=T() ) : x(std::move(x_)), y(std::move(y_))
    {
    }

    template<typename U>
    point operator>>( U offset ) const
    {
        point pt( *this );
        pt.x += offset;
        return pt;
    }

    T x;
    T y;
};

#include <iostream>
using namespace std;

int main( void )
{
    point pt( 1, 2 );
    cout << pt.x << endl;

    point tmp = pt>>3;
    cout << tmp.x << endl;
}
1