1.立方体
#include <iostream>
using namespace std;//立方体类设计
//1.创建立方体类
//2.设计属性
//3.设计行为 获取立方体面积和体积
//4.分别利用全局函数和成员函数 判断两个立方体是否相等class Cube
{
public:int getL(){return m_L;}void setL(int L){m_L = L;}int getW(){return m_L;}void setW(int W){m_W = W;}int getH(){return m_H;}void setH(int H){m_H = H;}//获取立方体面积int calculateS(){return 2 * m_L + 2 * m_W + 2 * m_H;}//获取立方体体积int calculateV(){return m_L * m_W * m_H;}//利用成员函数判断两个立方体是否相等bool isSameByClass(Cube &c){if (m_L == c.getL() && m_W == c.getW() && m_H == c.getH()){return true;}return false;}
private:int m_L;int m_W;int m_H;
};//利用全局函数判断 两个立方体是否相等
bool isSame(Cube& c1, Cube& c2)
{if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH()){return true;}return false;
}int main()
{//创建立方体对象Cube c1;c1.setL(10);c1.setW(10);c1.setH(10);cout << "c1的面积为:" << c1.calculateS() << endl;cout << "c1的体积为:" << c1.calculateV() << endl;//创建第二个立方体Cube c2;c2.setL(10);c2.setW(10);c2.setH(10);cout << "c1的面积为:" << c2.calculateS() << endl;cout << "c1的体积为:" << c2.calculateV() << endl;//利用全局函数判断bool ret = isSame(c1, c2);if (ret){cout << "c1和c2是相等的" << endl;}else{cout << "c1和c2是不相等的" << endl;}//利用成员函数判断bool ret2 = c1.isSameByClass(c2);if (ret2){cout << "c1和c2是相等的" << endl;}else{cout << "c1和c2是不相等的" << endl;}system("pause");return 0;
}
2.点和圆的关系
封装思想
point.h(声明)
#pragma once//点类
class Point
{
public://设置xvoid setX(int x);//获取xint getX();//设置yvoid setY(int y);//获取yint getY();
private:int m_X;int m_Y;
};
point.cpp(实现)
#include"point.h"//设置x
void Point::setX(int x)
{m_X = x;
}
//获取x
int Point::getX()
{return m_X;
}//设置y
void Point::setY(int y)
{m_Y = y;
}
//获取y
int Point::getY()
{return m_Y;
}
circle.h
#pragma once
#include<iostream>
#include"point.h"//圆类
class Circle
{
public://设置Rvoid setR(int r);//获取Rint getR();//设置圆心void setCenter(Point center);//在类中可以让另一个类 作为本来中的成员//获取圆心Point getCenter();
private:int m_R;Point m_Center;
};
circle.cpp
#include"circle.h"
#include"point.h"//设置Rvoid Circle::setR(int r){m_R = r;}//获取Rint Circle::getR(){return m_R;}//设置圆心void Circle::setCenter(Point center){m_Center = center;}//在类中可以让另一个类 作为本来中的成员//获取圆心Point Circle::getCenter(){return m_Center;}
main函数
#include <iostream>
#include"circle.h"
#include"point.h"using namespace std;//判断点和圆的关系
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 (distance == rDistance){cout << "点在圆上" << endl;}else if(distance>rDistance){cout << "点在圆外" << endl;}else{cout << "点在圆内" << endl;}
}
int main()
{//创建圆Circle c;c.setR(10);Point center;center.setX(10);center.setY(0);c.setCenter(center);//创建点Point p;p.setX(10);p.setY(11);//判断关系isInCircle(c,p);p.setY(10);isInCircle(c, p);
}