C++练习

一、程序填空题

点和线段

已知表示点的类CPoint和表示线段的CLine类,
类CPoint包含:(1)表达点位置的私有数据成员x,y
(2)构造函数及复制构造函数
类CLine包含:
(1)两个CPoint的点对象(该两点分别为线段的两个端点)
(2)构造函数(提示:构造函数中用初始化列表对内嵌对象进行初始化)
(3)公有成员函数GetLen,其功能为返回线段的长度,返回值类型为整型
(4)类属性成员count用于记录创建的CLine类对象的个数,及用于显示count值的ShowCount函数;
要求:
(1)实现满足上述属性和行为的CPoint类及CLine类定义;
(2)保证如下主函数能正确运行。

裁判测试程序样例:

/* 请在这里填写答案 */
int main(){
     int x,y;
     cin>>x>>y;
     CPoint p1(x,y);
     cin>>x>>y;
     CPoint p2(x,y);
     CLine line1(p1,p2);
     cout<<"the length of line1 is:"<<line1.GetLen()<<endl;
     CLine line2(line1);
     cout<<"the length of line2 is:"<<line2.GetLen()<<endl;
     cout<<"the count of CLine is:"<<CLine::ShowCount()<<endl; 
     return 0;
}

输入样例:

在这里给出一组输入。例如:

1 1 
4 5

输出样例:

在这里给出相应的输出。例如:

The length of line1 is:5
The length of line2 is:5
The count of Line is:2

答案如下:

#include <iostream>
#include <cmath>
using namespace std;

class CPoint {
private:
    int x;
    int y;

public:
    // 构造函数
    CPoint(int a, int b) : x(a), y(b) {}

    // 拷贝构造函数
    CPoint(const CPoint& p) : x(p.x), y(p.y) {}

    // 返回点的横坐标
    int GetX() const { return x; }

    // 返回点的纵坐标
    int GetY() const { return y; }
};

class CLine {
private:
    CPoint p1;
    CPoint p2;
    static int count;

public:
    // 构造函数
    CLine(const CPoint& point1, const CPoint& point2) : p1(point1), p2(point2) {
        count++;
    }

    // 拷贝构造函数
    CLine(const CLine& line) : p1(line.p1), p2(line.p2) {
        count++;
    }
    //获取线段长度
    

    // 获取线段长度
    int GetLen() const {
        int dx = p1.GetX() - p2.GetX();
        int dy = p1.GetY() - p2.GetY();
        return (int) sqrt(dx * dx + dy * dy);
    }

    // 获取 CLine 对象的个数
    static int ShowCount() { return count; }
};

// 静态成员变量需要在类外进行初始化
int CLine::count = 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值