前置声明与头文件


使用前置声明

point.cpp文件

#include "point.h"

Point::Point(float x, float y):_x(x), _y(y) {}

point.h文件

// 在预编译期,防止重复引用
#ifndef _POINT_H_
#define _POINT_H_


/*
能用前置声明就用前置声明
啥时候用:
    没有使用类的成员属性或者方法时可以用
*/
// 添加前置声明
class Line;

class Point {
    friend class Line;
public:
    Point(float x = 0, float y = 0); 

private:
    float _x, _y;
};


#endif

line.h文件

#ifndef _LINE_H_
#define _LINE_H_
#include "point.h"

class Line {
public:
    Line(const Point& p1, const Point& p2);
    float getDistance();
private:
    Point p1, p2;
};



#endif

line.cpp文件

#include "line.h"
#include 

Line::Line(const Point& p1, const Point& p2):p1(p1), p2(p2) {}


float Line::getDistance() {
    return sqrt(pow(p1._x - p2._x, 2) + pow(p1._y - p2._y, 2));
}

使用头文件

point.cpp文件

#include "point.h"

Point::Point(float x, float y):_x(x), _y(y) {}

point.h文件

使用头文件,调用类的成员方法

// 防止重复引用
#ifndef _POINT_H_
#define _POINT_H_


#include "line.h"
//使用头文件



class Point {
    //调用类的成员方法
    friend float Line::getDistance();
    
public:
    Point(float x=0, float y=0); 

private:
    float _x, _y;
};


#endif

line.h文件

#ifndef _LINE_H_
#define _LINE_H_

//使用前置声明
class Point;

class Line {
public:
    Line(const Point& p1, const Point& p2);
    float getDistance();
private:
    //使用指针类型,不调用Point的默认构造函数
    Point *p1, *p2;
};



#endif

line.cpp文件

#include "line.h"
#include 
#include "point.h"


Line::Line(const Point& p1, const Point& p2) {
    this->p1 = new Point(p1);
    this->p2 = new Point(p2);
}


float Line::getDistance() {
    return sqrt(pow(p1->_x - p2->_x, 2) + pow(p1->_y - p2->_y, 2));
}

主函数文件调用

main.cpp文件

#include 
#include "point.h"
#include "line.h"

using namespace std;


int main() {
    
    Point p1{32.4f, 42.4f}, p2{24.9f, 23.5f};
    Line line(p1, p2);
    cout << line.getDistance() << endl;
    return 0;

}

文章作者: Axieyun
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Axieyun !
评论
评论
  目录