C++Note 分文件案例 (点和圆)
#include<iostream> 属于标准库的头文件 用 <>
#include "point.h" 不属于标准库的头文件用 ""
头文件一:
1 #pragma once//命名唯一 2 #include <iostream> 3 #include "point.h" 4 //头文件 .h :类的声明等内容 5 using namespace std; 6 class Circle//圆类 7 { 8 private: 9 Point p_Center;//圆心 10 //在类中可以让另一个类 做为本类中的成员 11 int c_R;//圆的半径 12 public: 13 void setRadius(int radius);//写入半径x 14 int getRadius();//读取半径y 15 void setCenter(Point center);//写入圆心 16 Point getCenter();//读取圆心 17 18 };
头文件二:
1 #pragma once//命名唯一 2 #include <iostream> 3 using namespace std; 4 class Point//点类 5 { 6 private: 7 int p_X;//点坐标x 8 int p_Y;//点坐标y 9 public: 10 void setX(int x);//写入点x 11 int getX();//读取点x 12 void setY(int y);//写入点y 13 int getY();//读取点y 14 };
源文件一:
1 #include "circle.h" 2 //源文件 .cpp :函数的实现 作用域的更改 3 void Circle::setRadius(int radius)//写入半径x 4 { 5 c_R = radius; 6 } 7 int Circle::getRadius()//读取半径y 8 { 9 return c_R; 10 } 11 void Circle::setCenter(Point center)//写入圆心 12 { 13 p_Center = center; 14 } 15 Point Circle::getCenter()//读取圆心 16 { 17 return p_Center; 18 }
源文件二:
1 #include "point.h" //整体缩进 shift + Tab 2 void Point::setX(int x)//写入点x 3 { 4 p_X = x; 5 } 6 int Point::getX()//读取点x 7 { 8 return p_X; 9 } 10 void Point::setY(int y)//写入点y 11 { 12 p_Y = y; 13 } 14 int Point::getY()//读取点y 15 { 16 return p_Y; 17 }
源文件三 主函数:
#include <iostream> #include "circle.h" #include "point.h" using namespace std; //设计一个圆类 Circle 和一个点类 Point 计算点和圆的关系 //1.点在圆外 2.点在圆上 3.点在圆内 void Relation(Point &p,Circle &c) { int distance = pow((c.getCenter().getX() - p.getX()), 2) + pow((c.getCenter().getY() - p.getY()), 2); //点到圆心距离的平方 int rDistance = pow(c.getRadius(), 2);//圆半径的平方 if (distance > rDistance) cout << "点在圆外" << endl; else if (distance == rDistance) cout << "点在圆上" << endl; else cout << "点在圆内" << endl; } int main() { Point cp; Circle c; cp.setX(0);//圆心x cp.setY(0);//圆心y c.setRadius(3);//半径 c.setCenter(cp);//写入圆心 x y Point p;//独立点 p.setX(3);//独立点x p.setY(0);//独立点y Relation(p, c);//独立点p和圆c system("pause"); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)