#include<iostream> using namespace std; class rectangle{ public: void setlw(int newL=0,int newW=0); void showarea(); private: int length,width,area; };//定义矩形类 void rectangle::setlw(int newL,int newW){ length=newL; width=newW; area=length*width; } inline void rectangle::showarea(){ cout<<"矩形的面积为:"<<area<<endl; } int main(){ rectangle myrectangle; cout<<"请输入长,宽:"<<endl; int l,w; cin>>l>>w; myrectangle.setlw(l,w); myrectangle.showarea(); return 0; }

#include<iostream> using namespace std; class Complex{ public: Complex(double a,double b); Complex(double a); void add(Complex &c); void show(); private: double real,imaginary; }; void Complex::add(Complex &c){ real+=c.real; imaginary+=c.imaginary; } void Complex::show(){ cout<<real<<(imaginary>0?'+':'-')<<imaginary<<"i"<<endl; } Complex::Complex(double a,double b){ real=a; imaginary=b; } Complex::Complex(double a){ real=a; imaginary=0; } int main(){ Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show(); return 0; }

通过对类的学习,能够将简单的现实世界中的对象以函数形式反映出来。
浙公网安备 33010602011771号