随笔 - 403  文章 - 0  评论 - 6  阅读 - 3254

5月22日打卡

例具有静态数据、成员函数的Point类

代码部分:

 

复制代码
#include<iostream>
using namespace std;
class Point {
private:
    int x, y;
    static int count;
public:
    Point(int x=0,int y=0):x(x),y(y)
    {
        count++;
    }
    Point(Point& p)
    {
        x = p.x;
        y = p.y;
        count++;
    }
    ~Point() { count--; }
    int getX() { return x; }
    int getY() { return y; }
    static void showCount() {
        cout << "Object count=" << count << endl;
    }
};
int Point::count = 0;
int main()
{
    Point a(4, 5);
    cout << "Point a:" << a.getX() << "," << a.getY();
    Point::showCount();
    Point b(a);
    cout << "Point B:" << b.getX() << "," << b.getY();
    Point::showCount();
    return 0;
}
复制代码

例5-6

题目描述:

使用友元函数计算两点间的距离。

代码部分:

复制代码
#include<iostream>
#include<cmath>
using namespace std;
class Point {
private:
    int x, y;
public:
    Point(int x = 0, int y = 0) :x(x), y(y) {};
    int getX() { return x; }
    int getY() { return y; }
    friend float dist(Point& p1, Point& p2)
    {
        double x = p1.x - p2.x;
        double y = p1.y - p2.y;
        return static_cast<float>(sqrt(x * x + y * y);
    }
};
int main()
{
    Point myp1(1, 1), myp2(4, 5);
    cout << "The distance is:";
    cout << dist(myp1, myp2) << endl;
    return 0;
}
复制代码

 

posted on   石铁生  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示