c++实验3

#include <iostream>
using namespace std;
class Juxing  //声明矩形类
{
public: //外部接口
      Juxing(float x,float y)
    {
          length=x;
          width=y;
       } 
       Juxing(){ } ;
       float area()
       {
           return length*width;
        } //计算矩形面积       
private:  //私有数据成员
  float length;
  float width;
};
int main()
{
    float length,width,s;
    cout<<"Enter the length and width"<<endl;
    cin>>length>>width; 
    Juxing (length,width);
    s=width*length;
    cout<<"area is"<<s<<endl; 
    return 0; 
 } 


 

 
using namespace std;
class Complex
{
public:
    Complex(float r1,float i1);
    Complex(float a1); 
    void add(Complex c2);
    void show();
private:
    float r,i;
};
Complex::Complex(float r1,float i1) 
{
    r=r1;i=i1;
}
Complex::Complex(float r1)
{
    r=r1;i=0;
}
void Complex::add(Complex c2)
{
    r=r+c2.r;i=i+c2.i;
}
void Complex::show()
{
    cout<<r<<"+"<<i<<"i";
 } 
 int main()
 {
     Complex c1(3,5);
    Complex c2=4.5;
    c1.add(c2);
    c1.show();
    return 0;
 }

 

 总结:1.构造函数的作用就是在对象被创建时利用特定的值构造对象,将对象初始化为一个特定的状态。

      2.构造函数在对象被创建的时候将被自动调用。

      3.对象的名字下要加下划线。

 

 

 

 

 

 










 

posted @ 2018-04-08 23:08  *烟雨行舟*  阅读(88)  评论(2)    收藏  举报