虚函数与继承(2)

3 篇文章 0 订阅
#include  < iostream >
#include 
< vector >

using   namespace  std;

inline 
void  print( char   * msg)
{
    cout 
<< " " << msg << endl;
}


class  A
{
public:
    
virtual void foo1()
    
{
        print(
"A:foo1");
    }

    
    
void foo2()
    
{
        print(
"A:foo2");
    }

}
;

class  B:  public  A
{
public
    
void foo1()
    
{
        print(
"B:foo1");
    }

    
    
void foo2()
    
{
        print(
"B:foo2");
    }

}
;

class  Test
{
public:
    Test(
char *msg, void (*fun)())
    
{
        msg_ 
= msg;
        fun_ 
= fun;
    }

    
    
void run()
    
{
        cout 
<< msg_ << endl;
        fun_();
    }

    
    
char *msg_;
    
void (*fun_)();
}
;

void  test1()
{
    A 
* a = new B();
    B 
* b = (B*)a;
    b
->foo1();
    b
->foo2();
    a
->foo1();
    a
->foo2();
    delete a;
}


void  test2()
{
    B 
*= new B();
    b
->foo1();
    b
->foo2();
    A 
*= b;
    a
->foo1();
    a
->foo2();
    delete b;
}


void  test3()
{
    B b;
    b.foo1();
    b.foo2();
    ((A)b).foo1();
    ((A)b).foo2();
}


void  test4()
{
    B b;
    b.foo1();
    b.foo2();
    A 
*= &b;
    a
->foo1();
    a
->foo2();
}


void  test5()
{
    A a;
    B
* b = (B*)&a;
    b
->foo1();
    b
->foo2();
    a.foo1();
    a.foo2();
}


int  main()
{
    vector
<Test *> tests;
    vector
<Test *>::iterator t_iterator;
    
    tests.push_back(
new Test("test1"&test1));
    tests.push_back(
new Test("test2"&test2));
    tests.push_back(
new Test("test3"&test3));
    tests.push_back(
new Test("test4"&test4));
    tests.push_back(
new Test("test5"&test5));
    
    
for (t_iterator=tests.begin(); t_iterator!=tests.end(); t_iterator++)
    
{
        (
*t_iterator)->run();
    }

    system(
"PAUSE");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值