请教专家,为什么下面的代码都是输出 A类的方法,而采用指针才能达到重载的目的。
1 #include <endian.h> 2 #include <iostream> 3 using namespace std; 4 5 class A 6 { 7 public: virtual void print(void) 8 { 9 cout << "A:print" <<endl; 10 } 11 }; 12 class B :public A 13 { 14 public: void print (void) override 15 { 16 cout << "B:print" <<endl; 17 } 18 }; 19 20 void print (A a) 21 { 22 a.print(); 23 } 24 void print (A *a) 25 { 26 a->print(); 27 } 28 int main() 29 { 30 31 A a;B b; 32 a.print(); //A:print 33 b.print(); //B:print 34 35 print(a); //A:print 36 print(b); //A:print 为什么这里还是打印的A:print??? 37 38 print(&a); //A:print 39 print(&b); //B:print 重载了,所以打印子类的 40 41 A *c = new B(); 42 c->print(); //B:print 43 delete c; 44 45 46 }
标签:才行,void,print,重载,include,指针 From: https://www.cnblogs.com/xhu218/p/16900956.html