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;
}
CRectangle::CRectangle(
int width,
int height){
this->width=width;
this->height=height;
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);
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;
cout<<
"Rect2 circum"<<pRect->circum()<<endl;
cout<<
"Rect2 area"<<(*pRect).circum()<<endl;
return 1;
}