第三次
4-11
#include <iostream.h>
using namespace std;
class Rectangle
{
public:
Rectangle(float length, float width)
{
Length = length;
Width = width;
}
double area();
private:
float Length;
float Width;
};
double Rectangle::area()
{
return Length*Width;
}
void main()
{
float length, width;
cout << "请输入矩形的长度:";
cin >> length;
cout << "请输入矩形的宽度:";
cin >> width;
Rectangle r(length, width);
cout << "长为 " << length << "宽为 " << width << "的矩形 的面积为:"
<< r.GetArea () << endl;
}
4-20
#include<iostream>
using namespace std;
class complex{
public:
complex(double a,double b);
void add(complex c2);
void show();
private:
double real,imaginary;
};
complex::complex(double a,double b){
real=a;
imaginary=b;
}
void complex::add(complex c2){
real+=c2.real;
imaginary+=c2.imaginary;
}
void complex::show(){
cout<<real<<"+";
cout<<imaginary<<"i"<<endl;
}
int main()
{
complex c1(3,5);
complex c2(4.5);
c1.add(c2);
c1.show();
return 0;
}
这次实验学习了类,通过构造函数、复制构造函数、析构函数来应用类。我对类的使用还不熟练,勉强看懂例题,按例题解题,还不能熟练应用。