今天学构造函数,析构函数,默认构造函数,拷贝构造函数,颇有所得。

来源:互联网 发布:php常用函数 编辑:程序博客网 时间:2024/05/20 07:36

题目:在rect.h中定义一个矩形类CRect,类中有两个成员变量m_x,m_y。
            有 5个 构造函数
            默认构造函数  CRect()
            一般构造函数CRect(int   x,int  y)
            构造正方形构造函数 CRect(int r)
            左上角点和右下角点构造矩形
            CRect(int  x1,int  y1,int x2,int y2)
            拷贝构造函数
            求矩形面积函数
            求矩形周长函数
            用自己定义的类 在主函数 中利用5种不同的构造函数创建5种不同的矩形,分别求周长和面积

 

源代码

#include<iostream.h>
class CRect
{
public:
 CRect()
 {
    cout<<"Defaylt Constructor called"<<endl;
 }      //默认构造函数
 CRect(int x,int y)
 {
    m_x=x;m_y=y;
    cout<<"矩形周长为:"<<2*(x+y)<<endl;
          cout<<"矩形面积为:"<<x*y<<endl;
 }//构造函数
 
 CRect(int r)
 {
   cout<<"矩形周长为:"<<4*r<<endl;
         cout<<"矩形面积为:"<<r*r<<endl;
 }//正方形
    CRect(int x1,int y1,int x2,int y2)
 {
    cout<<"矩形周长为:"<<2*((x2-x1)+(y2-y1))<<endl;
    cout<<"矩形面积为:"<<(x2-x1)*(y2-y1)<<endl;
 }//对角点构造矩形
 CRect(CRect &p)
 {
  m_x=p.m_x;
  m_y=p.m_y;
  cout<<"矩形周长为:"<<2*(m_x+m_y)<<endl;
        cout<<"矩形面积为:"<<m_x*m_y<<endl;
 }

private:
 int m_x,m_y;

};

#include<iostream.h>
#include"crect.h"
void main()
{
 CRect A;
 CRect a(1,2);
 CRect p(3);
 CRect n(4,6,8,10);
 CRect b(a);
}

0 0
原创粉丝点击