面向对象程序设计(C++)实验指导书.doc
文本预览下载声明
实验 1 类和对象
1.1实验目的和要求
(1) 理解类和对象的概念,掌握声明类和定义对象的方法。
(2) 掌握构造函数和析构函数的实现方法。
(3) 初步掌握使用类和对象编制C++程序。
(4) 掌握对象数组、对象指针和string类的使用方法。
(5) 掌握使用对象、对象指针和对象引用作为函数参数的方法。
(6) 掌握类对象作为成员的使用方法。
(7) 掌握静态数据成员和静态成员函数的使用方法。
(8) 理解友元的概念和掌握友元的使用方法。
1.2实验内容和步骤
输入下列程序
//test4-1.cpp
#includeiostream
using namespace std;
class Coordinate
{ public:
Coordinate(int x1,int y1)
{ x=x1;
y=y1;
}
Coordinate(Coordinate p);
~Coordinate()
{ cout”Destructor is calleded\n”;}
int getx()
{return x;}
int gety()
{return y;}
private:
int x,y;
};
Coordinate::Coordinate(Coordinate p)
{ x=p.x;
y=p.y;
cout”copy-initialization Constructou is called\n”;
}
int main()
{ Coordinate p1(3,4);
Coordinate p2(p1);
Coordinate p3=p2;
cout”p3=(“p3.getx()”,”p3.gety()”)\n”;
return(0);
}
写出程序的运行结果。
copy-initialization Constructou is called
copy-initialization Constructou is called
p3 =(3,4)
Destructor is calleded
Destructor is calleded
Destructor is calleded
将Coordinate类中带有两个参数的构造函数进行修改,在函数体内增添下述语句:
cout”Constructor is called.\n”;
写出程序的运行结果,并解释输出结果。
Constructor is called.
copy-initialization Constructou is called
copy-initialization Constructou is called
p3 =(3,4)
Destructor is calleded
Destructor is calleded
Destructor is calleded
(3)按下列要求进行调试:
在主函数体内,添加下列语句:
Coordinate p4;
Coordinata p5(2);
调试程序时会出现什么错误?为什么?如何对已有的构造函数进行适当修改?
调用函数时找不到对应的函数,因为没有定义不含参数的函数,和只含一个参数的构造函数,所以调用函数时找不到这样的函数,应该给构造函数赋初值。Coordinate(int x1=0,int y1=0)
(4)经过以上第(2)步和第(3)步的修改后,结合运行结果分析:创建不同的对象时会调用不同的构造函数。
//test4-1.cpp
#includeiostream
using namespace std;
class Coordinate
{ public:
Coordinate(int x1=0,int y1=0)
{ x=x1;
y=y1;
coutConstructor is called.\n;
}
Coordinate(Coordinate p);
~Coordinate()
{ coutDestructor is calleded\n;}
int getx()
{return x;}
int gety()
{return y;}
private:
int x,y;
};
Coordinate::Coordinate(Coordinate p)
{ x=p.x;
y=p.y;
coutcopy-initialization Constructou is called\n;
}
int main()
{ Coordinate p1(3,4);
Coordinate p2(p1);
Coordinate p3=p2;
Coordinate p4;
Coordinate p5(2);
cout201240420224李
显示全部