因此,我要完成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访问所有的grand / superb / magnificent属性和方法。换句话说,这里没有失败。任何人都可以给我一个例子或在代码中添加一些内容,这些内容可以清楚地向我展示为派生对象分配基数如何使事情搞砸吗? 最佳答案 不要使用C样式转换。他们不安全。 C ++引入了4种新的类型转换,您正在寻找的是dynamic_cast Magnificent * ps2 = dynamic_cast<Magnificent*>(pg); // If pg is a Magnificent // (or is a super class of // Magnificent) it works fine.// If pg is not a Magnificent (in this case) it will return NULL.当您使用C样式强制转换时,您正在告诉编译器忽略所有规则,并按照自己说的做(编译器很乐意做)。没有检查以确保您在做什么有意义。C ++样式转换的限制要大得多,并且每个转换都进行特定范围的转换。 dynamic_cast用于向上和向下转换类层次结构。关于c++ - 关于指针向下转换/继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3284646/
10-13 06:59