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;
}