立方体的类设计
设计立方体类,求出立方体的面积(2ad+2ac+2bc)和体积(a*b*c),分别用全局函数和成员函数判断两个立方体是否相等?
#include <iostream>
using namespace std;
class Cube{
private://数据,长宽高
int c_l;
int c_w;
int c_h;
public:
//写长宽高
void setl(int l){
c_l=l;
}
void setw(int w){
c_w=w;
}
void seth(int h){
c_h=h;
}
//读长宽高
int readl(void){
return c_l;
}
int readw(void){
return c_w;
}
int readh(void){
return c_h;
}
//计算面积
void area(void){
cout << "the area of cube is " << 2*c_l*c_w+2*c_l*c_h+2*c_w*c_h << endl;
}
//计算体积
void volume(void){
cout << "the volume of cube is " << c_l*c_w*c_h << endl;
}
//成员函数判断(类的内部,没有权限之分)
bool compareC(Cube &c){
if(c_l == c.c_l && c_w == c.c_w && c_h == c.c_h)
return true;
return false;
}
};
//全局函数
bool compare(Cube &c1, Cube &c2){
if(c1.readl() == c2.readl() && c1.readw() == c2.readw() && c1.readh() == c2.readh())
return true;
return false;
};
int main(int argc, char *argv[])
{
Cube A;
A.setl(10);
A.setw(10);
A.seth(10);
A.volume();
A.area();
Cube B;
B.setl(10);
B.setw(20);
B.seth(10);
B.volume();
B.area();
//全局函数
if(compare(A,B)== true)
cout << "=" <<endl;
else
cout << "!=" <<endl;
//成员函数
if(A.compareC(B) == true)
cout << "=" <<endl;
else
cout << "!=" <<endl;
}
点和圆的关系 的类设计
#include <iostream>
#include <math.h>
using namespace std;
class point{
private:
int p_x;
int p_y;
public:
void setxy(int x=0, int y=0){
p_x = x;
p_y = y;
}
int getx(void){
return p_x;
}
int gety(void){
return p_y;
}
};
class circle{
private:
point c_xy;
int R;
public:
void setcxy(int x=0, int y=0){
c_xy.setxy(x, y);
}
int getcx(void){
return c_xy.getx();
}
int getcy(void){
return c_xy.gety();
}
void setR(int r=0){
R = r;
}
int getR(void){
return R;
}
void relate(point pp){
int px, py, cx, cy;
px = pp.getx();
py = pp.gety();
cx = c_xy.getx();
cy = c_xy.gety();
if((pow((px-cx), 2)+pow((py-cy), 2))\
==pow(R, 2))
cout << "on the c" << endl;
if((pow((px-cx), 2)+pow((py-cy), 2))\
< pow(R, 2))
cout << "in the c" << endl;
if((pow((px-cx), 2)+pow((py-cy), 2))\
> pow(R, 2))
cout << "out the c" << endl;
if((pow((px-cx), 2)+pow((py-cy), 2))\
== 0)
cout << "at the cpoint" << endl;
}
};
int main(int argc, char *argv[])
{
//在圆心
point p;
circle c;
p.setxy();
c.setcxy();
c.setR(2);
c.relate(p);
cout << endl;
//在圆内
p.setxy(1,1);
c.relate(p);
cout << endl;
//在圆上
p.setxy(0,2);
c.relate(p);
cout << endl;
//在圆外
p.setxy(2,2);
c.relate(p);
}
类的大小
类内声明,类外定义成员函数
类的定义在头文件,成员函数在cpp文件
头文件中
cpp文件中
main中调用
注:本文档仅学习总结