码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-10-01 22:59:41      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:blog   print   理解   基类   run   names   mes   c++   code   

//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;
        }

 

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

标签:blog   print   理解   基类   run   names   mes   c++   code   

原文地址:http://www.cnblogs.com/ming-michelle/p/7617951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!