c++实验3

#include<iostream>
using namespace std;
class Rectangle
{
private:
    int length,width;
public:
    Rectangle()
    {
        length=0;width=0;
    }
    void set(int a,int b);
    int area();        
};
void Rectangle::set(int a,int b)
{
    length=a;width=b;    
} 
int Rectangle::area()
{
    return length*width;
}
int main()
{
    Rectangle c;
    int m,n,t;
    cout<<"请输入矩形的长宽高:"<<endl;
    cin>>m>>n;
    c.set(m,n);
    t=c.area(); 
    cout<<"矩形的面积是:"<<t<<endl;
    return 0;
}

这一题,让我更加熟悉对类的使用。构造函数的书写等。

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

这题,用到以类为函数形参,调用了默认的复制构造函数,还有就是构造函数的重载。

posted @ 2018-04-08 16:29  tacore  阅读(108)  评论(4编辑  收藏  举报