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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值