所以我正在完成prata的C++入门,我是你的RTTI。他表现出一系列的下降,只是说这是错误的,但我想看到一个更好的例子。关于指针向下转换/继承
class Grand
{
private:
int hold;
public:
Grand(int h=0) : hold(h) {}
virtual void Speak() const { cout << "I am a grand class\n";}
virtual int Value() const {return hold; }
void Gah() const {cout << "ok" << endl;}
};
class Superb : public Grand
{
public:
Superb(int h = 0) : Grand(h){}
void Speak() const {cout << "I am a superb class!!\n";}
virtual void Say() const
{ cout << "I hold the superb value of " << Value() << "!\n";}
void Sah() const { cout << "Noak" << endl;}
};
class Magnificent : public Superb
{
private:
char ch;
public:
int hour;
Magnificent(int h = 0, char c = 'A') : Superb (h), ch(c){}
void Speak() const {cout << "I am a magnificent class!!!\n";}
void Say() const {cout << "I hold the character " << ch <<
"and the integer " << Value() << "!\n";}
void Mah() const {cout << "Ok" << endl;}
};
Grand * GetOne();
int _tmain(int argc, _TCHAR* argv[])
{
/*
srand(time(0));
Grand * pg;
Superb * ps;
*/
Grand * pg = new Grand;
Grand * ps = new Superb;
Grand * pm = new Magnificent;
Magnificent * ps2 = (Magnificent *)pg;
ps2->Gah();
cout << ps2->hour << endl;
system("pause");
}
因此,上面我将一个基础投射到一个总体上不被完成的派生。然而,在这个例子中,我真的只限于?当我投Pg时,我仍然可以通过ps2访问所有宏伟/精湛/宏伟的属性和方法。换句话说,这里没有任何失败。任何人都可以给我一个例子或添加一些代码,这将清楚地向我展示如何分配一个基地派生可以搞砸了吗?
好吧,现在明白了,但上面的例子运行的是基础打印而不是派生的打印,即使它们是虚拟功能... – Ilya 2010-07-19 20:56:00
是的,意识到发布后。更新了多个继承的示例,其中'base'不是第一个基类。 – 2010-07-19 21:28:31