实验3
验证性实验部分
在面向对象程序设计中,程序模块是由类构成的。类是对问题的抽象描述,在类这种抽象机制中的一个特定实体即为对象。而利用特定的值去构造对象,将对象初始化为特定状态即为构造函数,使用已经存在的对象去初始化同类的新对象即为复制构造函数,析构函数则是用来完成生存期即将结束的对象在被删除前的一些清理工作。
编辑实验部分
1
#include<iostream> using namespace std; class Rectangle{ public: Rectangle(float l,float w); Rectangle(Rectangle &r); float area(); ~Rectangle(){} private: float length,width; }; Rectangle::Rectangle(float l,float w){ length=l;width=w; } Rectangle::Rectangle(Rectangle &r){ length=r.length; width=r.width; } float Rectangle::area(){ return length*width; } int main(){ float length,width; cout<<"Enter the length and width of the rectangle:"; cin>>length>>width; Rectangle s(length,width); float areaofrectangle=s.area(); cout<<"The area of the rectangle is:"<<areaofrectangle<<endl; return 0; }
2
#include<iostream> using namespace std; class Complex{ public: Complex(double a,double b); Complex(double a); Complex(Complex &s); void add(Complex &c); void show(); ~Complex(){} private: double real,imaginary; }; Complex::Complex(double a,double b){ real=a; imaginary=b; } Complex::Complex(double a){ real=a; imaginary=0; } void Complex::add(Complex &c){ real=real+c.real; imaginary=imaginary+c.imaginary; } void Complex::show(){ cout<<real<<"+"<<imaginary<<"i"; } Complex::Complex(Complex &s){ real=s.real; imaginary=s.imaginary; cout<<"Calling the copy constructor"<<endl; } int main(){ Complex c1(3,5); Complex c2(4.5); c1.add(c2); c1.show(); return 0; }
实验总结与体会
学好计算机语言需要读懂书本,多动手