C++5-2 point个数

通过本题目的练习可以掌握静态数据成员和静态成员函数的用法。

要求设计一个点类Point,它具有两个double型的数据成员x、y,和一个静态数据成员count,用以记录系统中创建点对象的数目。为该类设计构造函数和析构函数,在其中对count的值做修改,体现点的数目的动态变化。并为其添加一个静态成员函数showCount用以输出count的值;成员函数showPoint()用于输出点的信息。

确保你严格按照题目要求定义Point类和它的成员函数,我们将在你提交的代码后追加一段代码用来检查Point类的定义。如果你的代码没有完全按照题目要求,将可能引发编译错误。

输入描述

输入点的x坐标和y坐标,当x、y均为0的时候停止输入。

输出描述

输出输入的点的个数。

示例1:

输入:1 1

           2 2

           3 3

           4 4

           0 0

输出:4

// 代码来源:https://my.oschina.net/u/4255005/blog/3721857

#include <iostream>
using namespace std;

class Point {
public:
    Point(double xx = 0.0, double yy = 0.0) :x(xx), y(yy) { count++; } // 构造函数1
    Point(const Point &p);// 构造函数2
    ~Point();
    static int showCount();
    void showPoint();
private:
    double x, y;
    static int count;
};

int Point::count = 0;

Point::Point(const Point&p) // 构造函数2的初始化
{
    x = p.x;
    y = p.y;
    count++;
}

Point::~Point() // 析构函数的初始化
{
    count--;
}

int Point::showCount()
{
    return Point::count;
}

void Point::showPoint()
{
    cout << x << " " << y << endl;
}

int main()
{
    double a, b;
    Point *save_point[100]; // 超纲!!!指针,数组
    int i = 0;
    while (cin >> a >> b)
    {
        if (a == b && a == 0)
        {
            cout << Point::showCount() << endl;
            break;
        }
        save_point[i] = new Point(a, b);
        i++;
    }
    // system("pause");
    return 0;
}


// 以下代码作废
/*
#include<iostream>
using namespace std;

class Point
{
public:
  Point(double a=0.0, double b=0.0); // 构造函数
  ~Point(){count--;} // 析构函数
  double showPoint();
  static int showCount();
private:
    double x,y;
    static int count;//静态数据成员的声明
};

Point::Point(double a, double b) // 构造函数类外初始化
{
  x=a;
  y=b;
  count++;
}

double Point::showPoint()
    {
        cout << "X=" << x << ",Y=" << y <<endl;
    }

int Point::showCount()
    {
      // cout << count << endl;
      return count;
    }

int Point::count=0;//静态数据成员的定义和初始化


int main()
{
  
  double x,y;
  // cin >> x >> y;
  // Point p(0,0);
  // int i=0;
  
  if(cin >> x >> y)
 
    // cin>>x>>y;
 	Point p(x,y);
   
 
    // Point p1(0,0);
    // p1.ShowPoint();
    // Point p2(3,0);
    // Point p3(5,0);
  else
  cout << Point::showCount() << endl;//类名::函数名  调用静态成员函数

    return 0;
}
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值