//4-11
//定义一个矩形类,有长宽两个属性,由成员函数计算矩形的面积 #include<iostream> using namespace std; //定义类 rectangle class rectangle{ public: //公共成员接口 rectangle(double l,double w); //构造函数 rectangle(rectangle &R0); //复制构造函数 ~rectangle(); //析构函数 double area(double length,double width){ return length*width; }; //计算矩形面积,内联函数 private: //私有成员接口 double length; double width; }; // 构造函数初始化数据成员 rectangle::rectangle(double l,double w){ length = l; width = w; } //复制析构函数初始化数据成员 rectangle::rectangle(rectangle &R0){ length = R0.length; width = R0.width; } //实现析构函数 rectangle::~rectangle() { } //主函数 int main(){ double length,width; cout << "enter the length of the rectangle :" ; cin >> length; cout << "enter the width of the rectangle :"; cin >> width; rectangle R1(length,width); //定义rectangle类的对象R1 cout << "the area of the rectangle is :" << R1.area(length,width) << endl; return 0; }
运行截图:

//4-20
//定义一个复数类
#include<iostream>
using namespace std;
class Complex{
public:
Complex(float r1,float i1);
Complex(float r1);
void add(Complex &c);
void show();
private:
float r;
float i;
};
//构造函数初始化
Complex::Complex(float r1,float i1){
r=r1;
i=i1;
}
//add函数
void Complex::add(Complex &c){
r+=c.r;
i+=c.i;
}
//show函数
void Complex::show(){
cout<<r<<(i>0 ? ‘+‘:‘-‘)<<i<<‘i‘<<endl;
}
//构造函数初始化
Complex::Complex(float r1){
r=r1;
i=0;
}
//主函数
int main(){
Complex c1(3,5); //用复数3+5i初始化c1
Complex c2=4.5; //用实数4,5初始化c2
c1.add(c2); //将c1与c2相加,结果保存在c1中
c1.show(); //输出c1
return 0;
}
运行截图:

原文:https://www.cnblogs.com/ANXX/p/8748050.html