标题:有关虚函数通过基类指针或基类引用实现动态多态性,求指教
取消只看楼主
Eliza
Rank: 1
等 级:新手上路
帖 子:13
专家分:0
注 册:2013-7-12
结帖率:100%
已结贴  问题点数:20 回复次数:2 
有关虚函数通过基类指针或基类引用实现动态多态性,求指教
示例37:阅读下面程序,写出输出结果。
#include <iostream>                                                   // 编译预处理命令
using namespace std;                                                               // 使用命名空间std

class A
{
public:
         virtual void Show1() const { cout << "A" << endl; }         // 输出信息
         void Show2() const { cout << "A" << endl; }                  // 输出信息
};

class B: public A
{
public:
         void Show1() const { cout << "B" << endl; }                  // 输出信息
         void Show2() const { cout << "B" << endl; }                  // 输出信息
};

void Fun1(A obj) { obj.Show1(); }                                             // 定义Fun1()                  
void Fun2(const A &obj) { obj.Show1(); }                           // 定义Fun2()

int main()                                                                                 // 主函数main()
{
         B obj;                                                                        // 定义对象
         A *p = &obj;                                                               // 指针
         p->Show1();                                                               // 输出信息
         p->Show2();                                                               // 输出信息
         Fun1(obj);                                                                        // 调用Fun1()
         Fun2(obj);                                                                        // 调用Fun2()
         
         return 0;                                                        // 返回值0, 返回操作系统
}
请问这程序是怎么理解的,我感觉很混乱,不好记住,求指教
搜索更多相关主题的帖子: include public 多态性 虚函数 动态 
2013-07-20 17:16
Eliza
Rank: 1
等 级:新手上路
帖 子:13
专家分:0
注 册:2013-7-12
得分:0 
回复 2楼 yuccn
多态,关键不理解
2013-07-20 18:06
Eliza
Rank: 1
等 级:新手上路
帖 子:13
专家分:0
注 册:2013-7-12
得分:0 
回复 7楼 peach5460
void Fun2(const A &obj) { obj.Show1(); }

主函数中Fun2(obj);是调用基类还是派生类的Show1
2013-07-21 17:14



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-417696-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.429622 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved