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