/* class_protect.class */
/* 基類轉(zhuǎn)換派生類問題:(不安全的轉(zhuǎn)換)
既然轉(zhuǎn)換了那就是指向派生類了,調(diào)用函數(shù)不涉及到變量還可以,
如果涉及到變量就是不安全的了,
如果是基類轉(zhuǎn)派生類, 那么基類不含有派生類的成員,?這樣調(diào)用就可能出現(xiàn)安全問題??
*/
/*? 派生類轉(zhuǎn)基類 (安全的轉(zhuǎn)換)?
比較常規(guī)的做法是派生類指針轉(zhuǎn)換成基類的? */
/*??
#include <iostream>
#include <cstring>
using namespace std;
/* ================? CLASS BOX ================== */
class Box
{
private:
double height;
protected:
double width;
public:
void setHeight(double h);
double getHeight(void);
};
void Box::setHeight(double h)
{
height = h;
}
double Box::getHeight(void)
{
return height;
}
/* ================== CLASS SMALLBOX =========================== */
class SmallBox : Box
{
public:
void setSmallWidth(double wid);
double getSmallWidth(void);
void setSmallHeight(double h);
double getSmallHeight(void);
};
double SmallBox::getSmallWidth()
{
return width;
}
void SmallBox::setSmallWidth(double wid)
{
width = wid;
}
void SmallBox::setSmallHeight(double h)
{
setHeight(h);
}
double SmallBox::getSmallHeight(void)
{
return getHeight();
}
/* ==========================? MAIN ======================= */
int main()
{
SmallBox *small = new SmallBox();
/* 訪問順序? 派生類public函數(shù) -> 基類public成員 */
small->setSmallWidth(5.0);
cout << "SmallWidth:" << small->getSmallWidth() << endl;
/* 訪問順序 派生類public函數(shù) -> 基類public函數(shù) -> 基類private成員? */
small->setSmallHeight(11.01);
cout << "getSmallHeight:" << small->getSmallHeight() << endl;
/* 派生類轉(zhuǎn)換成基類 */
Box *b = (Box *)small;
cout << "Before convert , Box Height: " << b->getHeight() << endl;
/* 基類設(shè)置height */
b->setHeight(20.01);
/* 結(jié)果都是 20.01 */
cout << "After convert Box Height: " << b->getHeight() << endl;
cout << "After convert SmallBox Height: " << small->getSmallHeight() << endl;
return 0;
}