.h文件与.cpp文件分开
实际项目中,主要用c++的部分——框架(MFC,QT,COCOX2d)
现有代码:两个类——圆类和点类,程序实现判断圆与点的位置。
为项目添加mycircle.h文件:(内容)
1 #pragma once //避免该文件被重复包含 2 #include "MyPoint.h" //包含另外一个头,因为在里面定义了点类,而这里使用到了点类型:void judge(MyPoint &p); 3 4 class MyCircle 5 { 6 public: 7 void setCircle(int _x1, int _y1, int _r); 8 9 void judge(int x0, int y0); 10 11 //类做函数参数的时候,类封装了属性和方法,在被调用函数里面, 不但可以使用属性,而且可以使用方法(成员函数); 12 //这也是面向对象和面向过程的一个重要区别。。。。 13 void judge(MyPoint &p); 14 15 private: 16 //定义圆心和圆的半径 17 int x1; 18 int y1; 19 int r; 20 21 };
为项目添加mycircle.cpp文件:(内容)
1 #include "iostream" 2 #include "MyCircle.h" //包含头文件 3 using namespace std; 4 5 void MyCircle::setCircle(int _x1, int _y1, int _r) 6 { 7 x1 = _x1; 8 y1 = _y1; 9 r = _r; 10 } 11 void MyCircle::judge(int x0, int y0) 12 { 13 int a = (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) - r*r; 14 if (a > 0) 15 { 16 cout<<"点在圆外"; 17 } 18 else 19 { 20 cout<<"点在圆内"; 21 } 22 } 23 24 //类做函数参数的时候,类封装了属性和方法,在被调用函数里面, 不但可以使用属性,而且可以使用方法(成员函数); 25 //这也是面向对象和面向过程的一个重要区别。。。。 26 27 void MyCircle::judge(MyPoint &p) 28 { 29 int a = (x1-p.getX())*(x1-p.getX()) + (y1-p.getY())*(y1-p.getY()) - r*r; 30 if (a > 0) 31 { 32 cout<<"点在圆外"; 33 } 34 else 35 { 36 cout<<"点在圆内"; 37 } 38 }
为项目添加myPoint.h文件:(内容)
1 #pragma once //避免重复包含该文件 2 class MyPoint 3 { 4 public: 5 void setP(int _x0, int _y0); 6 7 int getX(); 8 9 int getY(); 10 11 private: 12 //定义圆心和圆的半径 13 int x0; 14 int y0; 15 16 };
为项目添加myPoint.cpp文件:(内容)
1 #include "iostream" 2 #include "MyPoint.h" 3 using namespace std; 4 5 void MyPoint::setP(int _x0, int _y0) 6 { 7 x0 = _x0; 8 y0 = _y0; 9 } 10 int MyPoint::getX() 11 { 12 return x0; 13 } 14 int MyPoint::getY() 15 { 16 return y0; 17 }
最后编写主函数:
1 #include "iostream" 2 3 #include "MyCircle.h" 4 #include "MyPoint.h" 5 6 7 using namespace std; 8 9 void main() 10 { 11 MyPoint myp; 12 MyCircle c1; 13 14 myp.setP(1, 1); 15 c1.setCircle(2, 2, 3); 16 c1.judge(myp); 17 18 system("pause"); 19 system("pause"); 20 }

内在的趣味,表面的繁琐

浙公网安备 33010602011771号