C++中基类对象的引用

代码:

1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 class A{
 7     public:
 8         void print(){
 9         //virtual void print(){
10             cout<<"A"<<endl;
11         }
12 };
13 class B:public A{
14     public:
15         void print(){
16             cout<<"B"<<endl;
17         }
18 };
19 
20 int main(){
21 
22     B b;
23     A& a = b;
24     a.print();
25 
26     return 0;
27 }

输出:

A

若将A中的print()函数改成虚函数,则输出

B

分析:

由以上代码可知,基类对象的引用和指针实际上是非常相似的。
原文链接: https://www.cnblogs.com/hu983/p/5531641.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/234022

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午4:06
下一篇 2023年2月13日 下午4:06

相关推荐