随笔 - 398  文章 - 0  评论 - 6  阅读 - 3205

5月24日打卡

例5-9常引用做形参

 

复制代码
#include<iostream>
#include<cmath>
using namespace std;
class Point {
public:
    Point(int x=0,int y=0):x(x),y(y){}
    int getX() { return x; }
    int getY() { return y; }
    friend float dist(const Point& p1, const Point& p2);
private:
    int x, y;
};
float dist(const Point& p1, const 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()
{
    const Point myp1(1, 1), myp2(4, 5);
    cout << "The distance is:";
    cout << dist(myp1, myp2) << endl;
    return 0;
}
复制代码

 例5-10具有静态数据、函数成员的Point类,多组织文件

复制代码
class Point {
public:
    Point(int x = 0, int y = 0) :x(x), y(y) { count++;}
    Point(const Point& p);
    ~Point() { count--; }
    int getX()const { return x; }
    int getY()const { return y; }
    static void showCount();
private:
    int x, y;
    static int count;
};
#include"Point.h"
#include<iostream>
using namespace std;
int Point::count = 0;
Point::Point(const Point& p) :x(p.x), y(p.y)
{
    count++;

}
void Point::showCount() {
    cout << "Object count=" << count << endl;
}
#include"Point.h"
#include<iostream>
using namespace std;
int main()
{
    Point a(4, 5);
    cout << "Point A:" << a.getX() << "," << a.getX();
    Point::showCount();
    Point b(a);
    cout << "Point B:" << b.getX() << "," << b.getY();
    Point::showCount();

}
复制代码

 

posted on   石铁生  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 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

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