BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #45459同步于 2010/10/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

问个笔试题吧.

kmplayer
2010/10/30镜像同步18 回复
#include <iostream> using namespace std; class Base { public: virtual void f() { cout << "Base" << endl; } }; class Derive : public Base { public: virtual void f() { cout << "Derive" << endl; } }; int main() { Derive* d = new Derive; d -> f(); Base* b = d; b -> f(); //正常的多态性 Base* b2 = (Base*)d; b2 -> f(); //输出Derive,这是为什么呢??? }
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
lzlj机器人#1 · 2010/10/30
因为b2指针所指向的仍然是一个Derive对象啊
kmplayer机器人#2 · 2010/10/30
谢谢ls,继续请教 #include <iostream> using namespace std; class Base { public: virtual void f() { cout << "Base" << endl; } }; class Derive : public Base { public: virtual void f() { cout << "Derive" << endl; } }; int main() { Derive* d = new Derive; d -> f(); Base* b = d; b -> f(); //正常的多态性 Base* b2 = (Base*)d; b2 -> f(); //输出Derive,这是为什么呢??? Base b3 = (Base)(*d); //输出Base, 难道是调用拷贝构造函数? b3.f(); }
Vampire机器人#3 · 2010/10/30
因为b3的类型是Base,不是指针不是引用不多态
kmplayer机器人#4 · 2010/10/30
正解啊. 晕了...静态绑定啊. 【 在 Vampire 的大作中提到: 】 : 因为b3的类型是Base,不是指针不是引用不多态 : -- : ------------------------------- : ...................
zcenthink机器人#5 · 2010/10/31
(Base*)d和(Base)(*d)有什么区别吗?求详解
shenlei机器人#6 · 2010/10/31
指针:第一个是个基类类型的指针,实际还是指向派生类对象... 对象:第二个是把一个派生类对象转化为基类对象,实际也是基类... 【 在 zcenthink (时光) 的大作中提到: 】 : (Base*)d和(Base)(*d)有什么区别吗?求详解
h0ngyue机器人#7 · 2010/10/31
受教了!
hman机器人#8 · 2010/10/31
Base b3 = (Base)(*d); 这种用法好高级阿,这算是?
hman机器人#9 · 2010/10/31
果然是拷贝构造函数,真是高级阿。 #include <iostream> using namespace std; class Base { public: Base(){cout << "Base" << endl;} Base(const Base& C) // 拷贝构造函数 { cout << "copy constructure Base::()" << endl; } virtual void f() { cout << "Base::f()" << endl; } }; class Derive : public Base { public: Derive(){cout << "Derive" << endl;} Derive(const Derive& C) // 拷贝构造函数 { cout << "copy constructure Derive::()" << endl; } virtual void f() { cout << "Derive::f()" << endl; } }; int main() { cout << "...constructing d" << endl; Derive* d = new Derive; d -> f(); cout << "...constructing b" << endl; Base* b = d; b -> f(); //正常的多态性 // Base* b2 = (Base*)d; // b2 -> f(); //输出Derive,这是为什么呢??? cout << "...constructing b3" << endl; Base b3 = (Base)(*d); //输出Base, 难道是调用拷贝构造函数? b3.f(); }