案例
-
-
- .h中写类的成员函数声明
- .cpp 中写成员函数实现
-
.cpp文件
#define _CRT_SECURE_ND_WARNINGS
#include<iostream>
#include<string>
using namespace std;
#include"circle.h"
#include"point.h"
/*
设计一个圆类和一个点类,计算点和圆的关系
假如圆心坐标为x0,y0,半径为r,点的坐标为x1,y1
*/
//利用全局函数 判断点和圆的关系
void isInCircle(Circle &c, Point &p)
{
//获取圆心和点的距离 的平方
int distance = (c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) + (c.getCenter().getY() - p.getY())*(c.getCenter().getY() - p.getY());
int rDistance = c.getR() * c.getR();
if (rDistance == distance)
{
cout << "点在圆上" << endl;
}
else if (rDistance > distance)
{
cout << "点在圆内" << endl;
}
else
{
cout << "点在圆外" << endl;
}
}
void text01()
{
Point p1;
p1.setX(10);
p1.setY(10);
Circle c1;
Point center;
center.setX(10);
center.setY(0);
c1.setCenter(center);
c1.setR(10);
//利用局部判断点和圆的关系
isInCircle(c1, p1);
//利用成员函数判断点和圆的关系
c1.isInCircleByClass(p1);
}
int main()
{
text01();
system("pause");
return EXIT_SUCCESS;
}
point.h文件
#pragma once
#include<iostream>
using namespace std;
//.h 只做函数的声明,不做函数的实现
//点类
class Point
{
public:
void setX(int x);
/* {
m_X = x;
}*/
void setY(int y);
//{
// m_Y = y;
//}
int getX();
//{
// return m_X;
//}
int getY();
//{
// return m_Y;
//}
private:
int m_X;
int m_Y;
};
point.cpp文件
#include"point.h"
void Point::setX(int x)
{
m_X = x;
}
void Point::setY(int y)
{
m_Y = y;
}
int Point::getX()
{
return m_X;
}
int Point::getY()
{
return m_Y;
}
circle.h
#pragma once
#include<iostream>
using namespace std;
#include"point.h"
//圆类
class Circle
{
public:
//设置半径
void setR(int r);
//{
//m_R = r;
//}
//获取半径
int getR();
//{
// return m_R;
//}
//设置圆心
void setCenter(Point p);
//{
// m_Center = p;
//}
Point getCenter();
//{
// return m_Center;
//}
//利用成员函数判断点和圆的关系
void isInCircleByClass(Point& p);
//{
//获取圆心和点的距离 的平方
//int distance = (m_Center.getX() - p.getX()) * (m_Center.getX() - p.getX()) + (m_Center.getY() - p.getY()) * (m_Center.getY() - p.getY());
//int rDistance = m_R * m_R;
//if (rDistance == distance)
//{
// cout << "成员函数-点在圆上" << endl;
//}
//else if (rDistance > distance)
//{
// cout << "成员函数-点在圆内" << endl;
// }
//else
//{
// cout << "成员函数-点在圆外" << endl;
// }
//}
private:
int m_R;//半径
Point m_Center;//圆心
};
circle.cpp
#include"circle.h"
//设置半径
void Circle::setR(int r)
{
m_R = r;
}
//获取半径
int Circle::getR()
{
return m_R;
}
//设置圆心
void Circle::setCenter(Point p)
{
m_Center = p;
}
Point Circle::getCenter()
{
return m_Center;
}
//利用成员函数判断点和圆的关系
void Circle::isInCircleByClass(Point& p)
{
//获取圆心和点的距离 的平方
int distance = (m_Center.getX() - p.getX()) * (m_Center.getX() - p.getX()) + (m_Center.getY() - p.getY()) * (m_Center.getY() - p.getY());
int rDistance = m_R * m_R;
if (rDistance == distance)
{
cout << "成员函数-点在圆上" << endl;
}
else if (rDistance > distance)
{
cout << "成员函数-点在圆内" << endl;
}
else
{
cout << "成员函数-点在圆外" << endl;
}
}