c++——this指针 在类中指向 函数首地址

//this指针的作用
        #include"stdafx.h"
        #include<iostream>
        using namespace std;
        class CA
        {
            int a;
        public:
            CA(int i){ a = i; }
            void run(){ printf("CA run %d\n", a); }
        };
        //其中CA里面的run函数可以理解为如下代码、
        //void run(CA *const this)
        //{
        //    printf("CA run\n");
        //}

        class CB :public CA
        {
        public:
            CB(int i) :CA(i){}
            void run(){
                printf("CB run\n");
            }
        };
        void findRun(CA & a)  //没有定义成员变量呀
        {
            a.run();
        }
        //调用
        int main()
        {
            CA _1(1), _2(1);
            _1.run();    //this 指针的作用是找到_1的首地址
            _2.run();

            CA a(1);
            CB b(4);
            findRun(a);    //基类对象必然是一个基类对象,基类对象不是派生类对象
            findRun(b);//找到的两个都是a 的run函数
            return 0;
        }
        //--------------------------------------------------------------------
        //--------------------------------------------------------------------
        class CA
        {
            int a;
        public:
            CA(int i){ a = i; }
            void run(){ printf("CA run %d\n", a); }
        };
        //void run(CA *const this){printf("CA run %d\n", a);}
        //void run(CB* const this){printf("CB run %d\n", b);}
        class CB::public CA
        {
            int b;
        public:
            CB(int i, int m) :CA(i){ b = m; }
            void run(){ printf("CB run %d\n", b); }
        };
        int main()
        {
            CA a(1), *pa;
            CB b(4, 10), *pb;
            pa = &a, pa->run();//CA
            pb = &b; pb->run();//CB
            printf("//===========================\n");
            pa = &b;  pa->run();   //CA
            return 0;
        }

 

转载于:https://www.cnblogs.com/ming-michelle/p/7617951.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值