1、《面向对象程序设计》 上机报告 题目:第二次上机 班级: 学号: 姓名: 上机时间: 一、 题目要求 1.阅读程序,预测功能,再上机编辑、运行该程序,以验证自己的预测。 【思考与练习】 1. 构造函数的作用以及在什么情况下调用构造函数。 作用:不需要用户来调用它,在建立对象时自动识别它,有用户定义,根据初始化的要求设计函数体和函数参数。 2. 在什么情况下拷贝构造函数被调用。 在以下三种情况下,系统自动调用拷贝构造函数。 ⑴ 当用类的一个对象去初始化该类的另一个对象时; ⑵ 如果函数的形参是类的对象,调用函数,进行形参和实参的结合时; ⑶ 如果函数的返回值是
2、类的对象,函数执行完成返回调用者时。 3.构造一个圆柱体的类,定义该类对象a,再定义一个和a 同底等高的圆柱体b,计算 a 圆柱体的底面积,计算b 圆柱体的体积。 二 1.定义一个复数类,通过重载运算符: +,-,*,/,直接实现二个复数之间的乘除运算。编写一个完整的程序,测试重载运算符的正确性。要求加法“+”用成员函数实现重载,减法“-”用成员函数实现重载。乘法“*”用友元函数实现重载,除法“/”用成员函数实现重载。 ⑵上机要求 增加重载复数的加法和减法运算符的功能,实现两个复数的加法,一个复数与一个实数的加法;两个复数的减法,一个复数与一个实数的减法。用成员函数实现加法运算符的
3、重载,用友元函数实现减法运算符的重载。
自已设计主函数,完成程序的调试工作
二、题目分析
3,构造函数,通过调用函数实现运算。
2,运用运算符的重载。
三、源代码
1.1
#include
4、 int GetY(){ return Y; }
private:
int X,Y;
};
Point::Point(Point & p)
{
X = p.X;
Y = p.Y;
cout<<"调用拷贝构造函数\n";
}
void main()
{
Point A(3,4);
//Point B = A;
//Point B; B = A;
Point B(A); //b 行
cout< 5、\n";
}
1.2
#include 6、oint::Point(Point & p)
{
X = p.X;
Y = p.Y;
cout<<"调用拷贝构造函数\n";
}
void fun1(Point p)
{
cout< 7、
#include 8、X;
Y=p.Y;
cout<<"调用拷贝构造函数\n";
}
Point fun2()
{
Point Temp(10,20); //调用构造函数
return Temp;
}
void main()
{
Point A(4,5);
Point B(A);
cout< 9、 Point
{
public:
Point(int,int);
Point(Point &p);
int volume();
int area();
private:
int radius;
int height;
};
Point::Point(int r,int h)
{
radius=r;
height=h;
}
Point::Point(Point &p)
{
radius=p.radius;
height=p. 10、height;
cout<<"调用拷贝构造函数\n";
}
int Point::volume()
{
return(3.14159*radius*radius*height);
}
int Point::area()
{
return(3.14159*radius*radius);
}
int main()
{
Point c1(2,5);
cout<<"The area of c1 is "< 11、 cout<<"The volume of c2 is "< 12、lex c2);
friend Complex operator - (Complex c1,Complex c2);
void display();
private:
double real;
double imag;
};
Complex operator + (Complex c1,Complex c2)
{
return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
Complex operator - (Complex c1,Complex c2)
{
retur 13、n Complex(c1.real-c2.real, c1.imag-c2.imag);
}
void Complex::display()
{
cout<<"("< 14、
Press any key to continue
思考:
1,将b 行改写为Point B = A; 程序输出结果会有变化吗?
答:没有变化。
输出:
调用构造函数
调用拷贝构造函数
3
Press any key to continue
2,将b 行改写为Point B; B = A; 程序输出结果会有变化吗?
答:有变化。
输出:
调用构造函数
调用构造函数
3
Press any key to continue
1.2
输出:
调用构造函数
调用拷贝构造函数
4
调用拷贝构造函数
4
Press any key to continue
1.3
输出:
调用构造函数
调用拷贝构造函数
4
调用构造函数
调用拷贝构造函数
10
Press any key to continue
思考3
输出
The area of c1 is 12
调用拷贝构造函数
The volume of c2 is 62
Press any key to continue
2
输出
(3+13i)
(-1+-3i)
Press any key to continue
五、心得体会
通过这次上机,了解了运算符的重载,实现了复数的运算,也认识到了自己更多的不足,会继续努力。






