/* class_protect.class */
/* 基类转换派生类问题:(不安全的转换)
如果涉及到变量就是不安全的了,
如果是基类转派生类, 那么基类不含有派生类的成员, 这样调用就可能出现安全问题
*/
/* 派生类转基类 (安全的转换)
比较常规的做法是派生类指针转换成基类的 */
/*
#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函数 -> 基类public成员 */
small->setSmallWidth(5.0);
cout << "SmallWidth:" << small->getSmallWidth() << endl;
/* 访问顺序 派生类public函数 -> 基类public函数 -> 基类private成员 */
small->setSmallHeight(11.01);
cout << "getSmallHeight:" << small->getSmallHeight() << endl;
/* 派生类转换成基类 */
Box *b = (Box *)small;
cout << "Before convert , Box Height: " << b->getHeight() << endl;
/* 基类设置height */
b->setHeight(20.01);
/* 结果都是 20.01 */
cout << "After convert Box Height: " << b->getHeight() << endl;
cout << "After convert SmallBox Height: " << small->getSmallHeight() << endl;
return 0;
}
网友评论