2.1面向對象程序設計基礎

2.1.1類和對象

1.類的定義
格式:

 class 類名{
    public:
    ...
    private:
    ...
    protected:
    ...
};

2.類成員函數定義
格式:

void Picture::Chart(int i){
    ...
}
//::是作用域運算符

3.對象
格式:

Picture circle(0.5,(0,0));

2.1.2構造函數和析構函數

#include<iostream>

using namespace std;

class CRectangle
{
public:
    CRectangle();//默認構造函數
    CRectangle(int width,int height);//帶參數構造函數
    ~CRectangle();//析構函數
    double circum();
    double area();
private:
    int width;
    int height; //成員變量
};

CRectangle::CRectangle(){//定義默認構造函數
    this->width=10;
    this->height=5;
    cout<<"create default object"<<endl; 
    //非法語句?找不到cout?-no
}

CRectangle::CRectangle(int width,int height){//定義帶參構造函數

    this->width=width;
    this->height=height;//這個地方可以不用this->(貌似不行,編譯不過)
    cout<<"create new object"<<endl;
}

CRectangle::~CRectangle(){//析構函數(其實不需要定義)

    cout<<"delete object"<<endl;
}

double CRectangle::circum(){

    return 2*(width+height);
}

double CRectangle::area(){

    return width*height;
}

int main(){

    CRectangle Rect1,Rect2(30,20);  //Rect1默認,Rect2參數定義
    CRectangle *pRect=&Rect2;       //指針取地址
    //使用對象輸出周長和麪積
    cout<<"Rect1 circum"<<Rect1.circum()<<endl;
    cout<<"Rect1 area"<<Rect1.area()<<endl;
    cout<<"Rect2 circum"<<Rect2.circum()<<endl;
    cout<<"Rect2 area"<<Rect2.area()<<endl;
    //使用對象指針輸出Rect2周長和麪積
    cout<<"Rect2 circum"<<pRect->circum()<<endl;
    cout<<"Rect2 area"<<(*pRect).circum()<<endl;
    //等價表示?p->a==(*p).a
    //注意'.'>'*'
    return 1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章