目录
8章-类1
二级目录
三级目录
9章-类2
二级目录
信息保护-const对象,数据成员,成员函数,引用,指针
const: 即只读模式
常对象:
数据成员的值不能被改变,
定义时就初始化
常对象 只能调用const成员函数
普通对象 却也能调用const成员函数
二级目录
10章-运算符重载
二级目录
二级目录
11章-继承与派生
二级目录
二级目录
12章-虚函数与多态
习题
1 基类point下的 circle square move
绘制旋转图形
#include <iostream>
using namespace std;
class Point
{
double x;
double y;
public:
Point (double i,double j):x(i),y(j){}
void print ()const//不能改变数据成员 ,只是把这个坐标打印出来
{
cout<<"("<<x<<","<<y<<")";
}
};
class Figure
{
Point center;
public:
Figure(double i=0,double j=0):center(i,j){ }
Point& location()
{
return center;//把它的个center对象成员弄到手
}
void move(Point p)
{
center=p;//改变其坐标对象的值
draw();//然后再画出这个改变后的figure,draw函数在下边
}
virtual void draw()=0;
virtual void rotate(double)=0;
};
class Circle:public Figure
{
double radius;
public:
Circle(double i=0,double j=0,double r=0):Figure(i,j),radius(r){}
void draw()//对父类figure中的虚函数的实现
{
cout<<"A circle with center ";
location().print();
cout<<"and radius "<<radius<<endl;
}
void rotate(double)//
{
cout<<"no effect operation.\n";
}
};
class Square:public Figure
{
double side;
double angle;
public:
Square(double i=0,double j=0,double d=0,double a=0):Figure(i,j),side(d),angle(a){
}
void draw()
{
cout<<"A square with center ";
location().print();
cout<<" side length"<<side<<'\n'<<"the angle betwen one side and the x-axis is "<<angle<<endl;
}
void rotate(double a)
{
angle+=a;
cout<<"the angle between one side and the x-airs is "<<angle<<endl;
}
void vertices(){
cout<<"the vertices of the square are: 3\n";
}
} ;
int main ()
{
Circle c(1,2,3);
Square s(4,5,6);
Figure* f=&c;
Figure& g=s;
// Figure d;
// f=new Figure(10,10);//这两个创建抽象类的操作非法
f->draw();//f为基类指针,通过->访问。而g为引用直接用点.访问即可。
f->rotate(1);
f->move(Point(2,2)) ;
g.draw();
g.rotate(1);
g.move(Point(1,1));
s.vertices();
// g.vertices();//非法,基类指针不能访问非继承所得的成员 ,见下图解释
return 0;
}
知识点补充:
2
【例12-5】先建立一个Point(点)类,包含数据成员x,y(坐标点)。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径),再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)。要求编写程序,重载运算符“<<”和“>>”,使之能用于输出以上类对象。
分析:对于一个比较大的程序,应当分成若干步骤进行。先声明基类,再声明派生类,逐级进行,分步调试。
在这里插入代码片
3 老师ppt结尾的打怪例题–增强可扩充性示例***