当前位置:首页 > 实验指导(C++面向对象部分)
} // 构造函数,带默认参数,默认值为全0,在声明中指定 void Rectangle::Assign(int l, int t, int r, int b){ left = l; top = t;
right = r; bottom = b; }
void Rectangle::Show(){
cout<<\
cout<<\}//当用.h头文件时,不用endl输出次序可能出错 void Rectangle::operator+=(Rectangle& rect){ int x = rect.right - rect.left; int y = rect.bottom - rect.top; right += x; bottom += y; }
void Rectangle::operator-=(Rectangle& rect){ int x = rect.right - rect.left; int y = rect.bottom - rect.top; right -= x; bottom -= y; }
Rectangle operator- ( Rectangle &rect1, Rectangle& rect2){ //矩形相减,从rect1中减去rect2的长度和宽度 rect1 -= rect2; return rect1; }
Rectangle operator+ ( Rectangle &rect1, Rectangle& rect2){ //矩形相加,从rect1中加上rect2的长度和宽度 rect1 += rect2; return rect1; }
// 将上述内容保存为rect.cpp #include
Rectangle rect;
cout<<\初始rect:\ rect.Show();
rect.Assign(100,200,300,400); cout<<\赋值后rect:\ rect.Show();
Rectangle rect1(0,0,200,200); cout<<\初始rect1:\
rect1.Show(); rect+=rect1;
cout<<\与rect1相加后的rect:\ rect.Show(); rect-=rect1;
cout<<\减去rect1后的rect:\ rect.Show(); Rectangle rect2; rect2 = rect+rect1;
cout<<\与rect1相加所得rect2:\ rect2.Show(); rect2 = rect-rect1;
cout<<\减去rect1所得rect2:\ rect2.Show(); return 0; }
实验题2参考程序 #include
class shape // 抽象类的定义 {
public:
virtual double area()=0;
virtual double perimeter()=0; };
class circle:public shape // 圆类 {
protected:
double radius; public:
circle(double r) {radius=r;} double area()
{return radius*radius*3.14;} double perimeter() { return 2*radius*3.14;} };
class Outersquare:public circle //外切正方形 {
protected:
double border1; public:
Outersquare(double b):circle(b) {border1=2*b;}
double area()
{return border1*border1;} double perimeter() { return 4*border1;} };
class Innersquare:public circle // 内接正方形 {
protected:
double border2; public:
Innersquare(double b):circle(b) {border2=sqrt(2*b*b);} double area()
{return border2*border2;} double perimeter() { return 4*border2;} };
void main() {
shape *s; s=new circle(5.00);
cout<
s=new Outersquare(5.00);
cout<
cout<
【思考题】
1.如果一个类中存在大量的虚函数,会造成什么样的结果? 2.什么时候比较适合使用虚析构函数。
实验五 i/o流
【实验类型】验证性 【实验要求】必做
【实验目的】
1.了解i/o流类族的基本结构及类族中各个类的作用。
2.掌握常用的i/o流类成员函数和数据成员。掌握利用标准输入输出对象和用户自定义流对象调用i/o流类成员。
3.了解常用输入输出格式控制方法。
4.了解文件流的使用方法,掌握读,写,遍历文本文件和二进制文件。 【实验内容】
实验题1. 编写一个程序拷贝文本文件,在拷贝文件过程中,改变改变所有字母的大小写。
实验题2.从输入流中分析出数字串。
实验题3.将下列格式化数据输出到二进制文件epy.dat中。 名字 年龄 编号 工资
张一 30 s001 800.50 李二 28 s002 1010.00 王三 35 s003 950.30 【参考程序】 实验题1参考程序 #include
void main(int argc,char *argv[]) {
if (argc!=3) {
cout<<\ return ; }
ifstream in(argv[1]); if(!in) {
cout<<\不能打开输入文件!\ return ; }
ofstream out(argv[2]); if(!out) {
cout<<\不能打开输出文件!\ return ; }
char ch;
共分享92篇相关文档