资源描述
C++面向对象的程序设计
学院:经济管理学院
班级:061011
姓名:王秀洋
学号:06101002
实验目的:1、熟悉VC++6.0操作界面
2、学会编写简单的C++程序
3、掌握类的定义和使用
实验需求:1. 整理上机步骤,总结经验和体会。
2. 完成实验日志和上交程序。
实验步骤:1、操作界面
图一、Vc++6.0操作界面分区
2、建立工程项目
(1) 选择“文件”“新建”“工程”命令,然后选中Win32 Console Application选项,输入工程名称06101002创建新工程。
(2)新建一个“hello world!”,调试运行,得到结果后继续编写。
3、编写代码
(1)class一个父类Shape,抽象表示形状。编写头文件代码如下:
#ifndef SHAPE_H
#define SHAPE_H
class Shape //抽象类Shape,表示形状
{
protected:
double d;
public:
void setShape(double i) //几何参数
{ d=i;}
virtual void area()=0; //面积函数
virtual void volume()=0; //体积函数
};
#endif
(2)然后编写立体几何圆柱体、球行和正方形的头文件,代码如下:
①圆柱体
#ifndef Cylinder_H
#define Cylinder_H
class Cylinder: public Shape //圆柱体类
{ private:
double height;
public:
void setCylinder(double i,double j)
{
setShape(i);
height=j;
}
void area()
{ cout<<"圆柱体的表面积:"<<2*3.14*d*height+2*3.14*d*d<<endl;
}
void volume()
{ cout<<"圆柱体的体积:"<<3.14*d*d*height<<endl;
}
};
#endif
②球体
#ifndef Sphere_H
#define Sphere_H
class Sphere:public Shape //球体的类
{
public :
void setSphere(double i)
{setShape(i);}
void area()
{
cout<<"球体的表面积:"<<4*3.14*d*d<<endl;
}
void volume()
{
cout<<"球体的体积:"<<4/3*3.14*d*d*d<<endl;
}
};
#endif
③正方体
#ifndef Cube_H
#define Cube_H
class Cube:public Shape //正方体类
{
public:
void setCube(double i)
{
setShape(i);
}
void area()
{cout<<"正方体的表面积:"<<d*d*6<<endl;}
void volume()
{
cout<<"正方体的体积:"<<d*d*d<<endl;
}
};
#endif
(3)主程序
// 06101002.cpp : Defines the entry point for the console application.
//
#include <iostream.h>
#include "shape.h"
#include "Cylinder.h"
#include "Cube.h"
#include "Sphere.h"
int main()
{
Shape *p0;
double p ;double q;double r;
Cylinder cy1;
Sphere sp1;
Cube cu1;
p0=&cy1;
cout<<"分别输入圆柱体的半径和高:"<<endl;
cin>>p>>q;
cy1.setCylinder(p,q);
p0->area();
p0->volume();
p0=&sp1;
cout<<endl<<"输入球体的半径:"<<endl;
cin>>r;
sp1.setSphere(r);
p0->area();
p0->volume();
p0=&cu1;
cout<<endl<<"输入正方体的边长:"<<endl;
cin>>p;
cu1.setCube(p);
p0->area();
p0->volume();
return (0);
}
4、运行结果
以圆柱体半径2,高8;球体半径4;正方体边长4为例,运行程序得出结果如下:
图二、程序运行结果
试验中遇到的问题及解决办法:
(1)致命错误C1010:在寻找预编译指示头文件时,文件未预期结束。(fatal error C1010: unexpected end of file while looking for precompiled header directive)
就是没有找到预编译指示信息的头文件。
问题一般发生在:通过添加文件的方式,添加了一些cpp文件到一个MFC的程序,但该cpp文件并不是MFC,而是标准的C++。
解决方案1:在菜单工程->设置->C/C++->预编译的头文件,设置为第一项:不使用预补偿页眉。
解决方案2:在.cpp文件开头添加包含文件stdafx.h。 #include"stdafx.h"
(2)fatal error C1070: mismatched #if/#endif pair in file 'c:\users\administrator.pc-20111028fwwa\desktop\06101002\cube.h'即:
'c:\users\administrator.pc-20111028fwwa\desktop\06101002\cube.h' 文件中#if 与 #endif预编译指令不匹配
解决办法:在头文件最后加上#endif,作用是这样做是为了防止重复编译,不这样做就有可能出错。
展开阅读全文