我们研究一下继承和虚函数。
比如我们需要求正方形、长方形的周长、面积:
选择1计算长方形
选择2计算正方形
选择3退出
其他无效
我们做一个继承实现,父类矩形,子类有正方形、长方形继承矩形
C++的继承语法如下:
矩形
class Rectangle
正方形
class Square: public Rectangle
长方形
class Oblong: public Rectangle
对正方形、长方形求面积、周长。面积公式相同,在矩形父类完成,函数area();周长公式不同,在各个子类种实现。这里有一个虚函数side()。
/**
* 求边长
*/
virtual int side()=0;
让函数side()=0;是在此定义,由子类实现。类似于Java的抽象父类,指定需要子类实现的方法。
矩形类:
/**
* 矩形
*/
class Rectangle {
protected:
int a; // a边
int b; // b边
public:
/**
* 求面积
*/
int area() {
return a * b;
}
/**
* 求边长
*/
virtual int side()=0;
};
éè??á?a?¢bá?±??ò?aprotected1?×óàà?±?óê1ó?£???3?á??ó???yμ?oˉêyêμ??area£¨£?£?í?ê±?¨ò?á??ó±?3¤μ?oˉêyside£¨£?£?òa?óoˉêyside£¨£?óé×óààêμ???£
?y·?D?àà£o
/**
??* ?y·?D?
??*/
class Square: public Rectangle {
public:
?????? /**
???????? * éè??±?
???????? */
?????? void setA(int a) {
?????????????? this->a = a;
?????????????? this->b = a;
?????? }
?????? /**
???????? * ?ó±?3¤
???????? */
?????? virtual int side() {
?????????????? return 4 * a;
?????? }
};
êμ??á??ó±?3¤oˉêyside£¨£?£?í?ê±?óè?éè??±?oˉêysetA£¨int a£??£
3¤·?D?àà£o
/**
??* 3¤·?D?
??*/
class Oblong: public Rectangle {
public:
?????? /**
???????? * éè??a±?
???????? */
?????? void setA(int a) {
?????????????? this->a = a;
?????? }
?????? /**
???????? * éè??b±?
???????? */
?????? void setB(int b) {
?????????????? this->b = b;
?????? }
?????? /**
???????? * ?ó±?3¤
???????? */
?????? virtual int side() {
?????????????? return 2 * a * b;
?????? }
};
êμ??á??ó±?3¤oˉêyside£¨£?£?í?ê±?óè?éè??±?oˉêysetA£¨int a£?oísetB£¨int b£??£?ù?Yê?è?×??àó|????£o
/**
??* ????
??*/
inline void calculate() {
?????? int chioce; // ????
?????? int a; // a±?
?????? int b; // b±?
?????? Oblong o; // 3¤·?D?
?????? Square s; // ?y·?D?
?????? cout << endl;
?????? cout << "??????D?ààDí£o" << endl;
?????? cout << "1-3¤·?D?" << endl;
?????? cout << "2-?y·?D?" << endl;
?????? cout << "3-í?3?" << endl;
?????? cin >> chioce;
?????? switch (chioce) {
?????? case 1:
?????????????? cout << "ê?è?a±?£o";
?????????????? cin >> a;
?????????????? cout << "ê?è?b±?£o";
?????????????? cin >> b;
?????????????? o.setA(a);
?????????????? o.setB(b);
?????????????? cout << "???y?a£o" << o.area() << endl;
?????????????? cout << "?ü3¤?a£o" << o.side() << endl;
?????????????? calculate();
?????????????? break;
?????? case 2:
?????????????? cout
|