Friday, September 25, 2020

C Encapsulation

point.h 

=======================================================================

struct Point;

struct Point* makePoint(double x, double y);

double getDistance(struct Point *p1, struct Point *p2);

=======================================================================

point.c

=======================================================================

/* point.c */

#include "point.h"

#include <stdlib.h>

#include <math.h>

struct Point {

    double x, y;

}

struct Point* makePoint(double x, double y) {

    struct Point* p = malloc(sizeof(struct Point));

    p->x = x;

    p->y = y;

    return p;

}

double getDistance(struct Point* p1, struct Point *p2) {

    double dx = p1->x - p2->x;

    double dy = p1->y - p2->y;

    return sqrt(dx*dx + dy*dy);

=======================================================================

Compare C++

=======================================================================

point.h

=======================================================================

class Point {

public:

    Point(double x, double y);

    double getDistance(const Point& p) const;

private:

    double x;

    double y;

}

=======================================================================

point.cc

=======================================================================

#include "point.h"

#include <math.h>


Point::Point(double x, double y): x(x), y(y) {}


double Point::getDistance(const Point& p) const {

    double dx = x - p.x;

    double dy = y - p.y;

    return sqrt(dx*dx + dy*dy);

}

=======================================================================

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能