多态性C.
发布时间:2020-12-16 10:29:19 所属栏目:百科 来源:网络整理
导读:我想要打印代码: B BA BB A 但它打印 Item ItemItem ItemItem Item 代码: #include stdio.h#include stdlib.h#include iostreamusing namespace std;struct Item { Item(){} virtual void method1 (Item x,Item y) {cout "Item Itemn";}};struct A : publ
我想要打印代码:
B B A B B A 但它打印 Item Item Item Item Item Item 代码: #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct Item { Item(){} virtual void method1 (Item x,Item y) {cout << "Item Itemn";} }; struct A : public Item { A(){} }; struct B : public Item { B(){} virtual void method1 (B x,B y) {cout << "B Bn";} virtual void method1 (A x,B y) {cout << "A Bn";} virtual void method1 (B x,A y) {cout << "B An";} }; int main ( void ) { Item * a[2]; a[0] = new B; a[1] = new A; a[0]->method1(*a[0],*a[0]); a[0]->method1(*a[1],*a[0]); a[0]->method1(*a[0],*a[1]); } 解决方法
B中method1的重载不会覆盖Item中的虚方法.因此,当您调用someItem-> method1时,它不会使用它们.
看起来你想要所谓的“多次发送”,C不直接支持.有关讨论和解决方法,请参阅http://en.wikipedia.org/wiki/Multiple_dispatch#C.2B.2B. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |