实验5-类和对象

更新时间:2023-11-07 15:33:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

实验5 类和对象

程序填空

1.

本题分值:10

题目描述:仔细阅读下列求两个点之间距离的程序,程序的输出结果是50,根据程序的输出结果在划线处填入正确语句。 代码:

#include #include

using namespace std; class point {

public:

point(float a,float b) { x=a; y=b; } float Distance(point &p) {

float dx=__(1)__; float dy=__(2)__;

return (float)sqrt(dx*dx+dy*dy); } private:

float x,y; };

int main() {

point p1(2,3),p2(32,43); cout<<__(3)__<

答案:

(1) p.x-x (2) p.y-y

(3) p1.Distance(p2) 2.

本题分值:10

题目描述:设计一个矩阵类CRectangle,该类中的私有成员变量存放Rectangle的长和宽,并设置它们的默认值为1,通过成员函数set()来设定长和宽的值,并确保长宽都在(0,50)

范围之内,求其周长Perimeter并显示输出。以下是完成此项工作的程序,请将未完成的部分填入,使之完整。 代码:

#include using namespace std; class CRectangle {

public:

void Set(float a,float b) {

if((a>0)&&(a<50)) length=a; else length=1;

if((b>0)&&(b<50)) width=b; else width=1; }

float perimeter() {

return 2*(length+width); } private:

float length; float width; };

int main() {

CRectangle R;

float l,w;//定义矩形的长和宽做为输入变量; // cout<<\请输入矩形的长和宽:\ cin>>l>>w;

R.__(1)__; //设置矩形的长和宽

cout<<\矩形的周长为:\ return 0; }

答案:

(1) Set(l,w)

(2) R.perimeter() 3.

本题分值:10

题目描述:设计一个类Crectangle,要求如下所述。

(1)定义两个点坐标x1,y1,x2,y2,两点所确定的一条直线构成了矩形的对角线。

(2)初始化矩形的两个点时,判断给定的两个点是否能够构成一个矩形,如果不能构成矩形,则矩形对角线的两点初始化为(0,0)和(1,1)。如果可以构成,则用形参初始化对象

的数据成员。

根据以上描述完成下列程序。

代码:

#include #include

using namespace std; class CRectangle {

public:

CRectangle(float Rx1=0,float Ry1=0, float Rx2=1,float Ry2=1); bool IsSquare( );

void PrintRectangle( ); private:

//确定直线的两点的坐标 float x1,y1,x2,y2; };

CRectangle::CRectangle(float Rx1 ,float Ry1, float Rx2,float Ry2) {

if (__(1)__) //两点的横坐标或纵坐标的值相等,则不能构成矩形 {

x1=y1=0; x2=y2=1;

cout<<\不能构成矩形! \ } else {

__(2)__ //初始化数据成员x1,y1,x2,y2 cout<<\可以构成矩形! \ } }

int main() {

CRectangle R1(1,3,5,6); CRectangle R2(1,3,1,6); return 0; }

答案:

(1) (Rx1==Rx2)||(Ry1==Ry2)

(2) x1=Rx1; y1=Ry1; x2=Rx2; y2=Ry2; 4.

本题分值:10

题目描述:下列程序中声明了类girl,其中函数“display”是类girl的友元函数,请在(1)、(2)和(3)处各填入正确的内容,使程序能正常运行。 代码:

#include using namespace std; class girl {

private:

char name; int age; public:

girl(char n, int d) //构造函数 {

name= n; age=d; }

__(1)__ void display(girl &x); //声明友元函数 };

void display(__(2)__) //类外定义 友元函数 {

cout<<\ //girl类的友元函数能访问girl类对象的私有成员 }

int main( ) {

girl e('z',18);

__(3)__; //调用友元函数 return 0; }

答案: (1) friend (2) girl &x (3) display( e ) 5.

本题分值:10 题目描述:,请完善下面程序,使程序的运行结果如下:

This is a constructor ! This is a constructor ! The value of ch is a

The value of ch is b This is a destructor of b This is a destructor of a

代码:

#include using namespace std; class MyClass {

char ch; public:

MyClass( ) {

cout<<\ ch='a'; }

MyClass(char character ) {

cout<<\ ch=character; }

void Print( ) {

cout<<\ }

~ MyClass( ) {

cout<<__(2)__<

int main( ) {

MyClass first, __(3)__; first.Print( ); second.Print( ); return 0; } 答案: (1) ch

(2) \(3) second('b')

程序设计

6.

本题分值:10

题目标题:计算两点间的距离 时间限制:1000MS

本文来源:https://www.bwwdw.com/article/ol62.html

Top