首页 > 代码库 > virtue function c++
virtue function c++
之前一直不明白为什么要用虚函数,我只知道这样的规则, Base b = new derived(); b->do(); 调用的是子类的do();
virtue class只是一个虚拟的,调用的是子类
在不声明virtue的时候,b->do()调用的是指针所属的类的do(),而不是所指向子类的do()
看了下面这个例子恍然大悟理解virtue的奥秘 http://stackoverflow.com/questions/429125/override-and-overload-in-c
truct base { virtual void print() { cout << "base!"; }}struct derived: base { virtual void print() { cout << "derived!"; }}Now, if you have an object and call the print member function, the print function of the derived is always called, because it overrides the one of the base. If the function print wasn‘t virtual, then the function in the derived wouldn‘t override the base function, but would merely hide it. Overriding can be useful if you have a function that accepts a base class, and every one that‘s derived from it:void doit(base &b) { // and sometimes, we want to print it b.print();}
可以看出在doit里面,你可以传任何对象,只要是属于base的子类 这样1,你不用声明具体的类 2,多次重复给不同的子类使用
virtue function c++
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。