// ConsoleApplication19.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
using namespace std;
class TC
{
public:
static int ms_i;
int m_i;
int m_ii;
void normalFunc(int){
cout << "成员函数" << endl;
}
static void staticFunc(int){
cout << "属于类的静态函数" << endl;
}
virtual void normalVirtualFunc(int){
cout << "成员虚函数" << endl;
}
protected:
private:
};
void chengYuanHanShuZhiZhen(){
//-- 成员函数指针
//typedef
//void(TC:: * pFunc)(int) = & (TC::staticFunc); NG
//-- 定义一个类的 普通成员函数指针变量 的定义 并赋予初值
void(TC:: * pFunc)(int) = &(TC::normalFunc);
cout << "void(TC:: * pFunc)(int) = &(TC::normalFunc);" << &pFunc << endl;
//-- 定义一个类的 虚成员函数指针变量 并赋予初值
void(TC:: * pFunc2)(int) = &(TC::normalVirtualFunc);
cout << "void(TC:: * pFunc2)(int) = &(TC::normalFunc);" << &pFunc2 << endl;
//-- 定义一个类的 静态成员函数指针 并赋予初值
void(*pFunc3)(int) = &TC::staticFunc;
pFunc3(2);
//-- 一个类 成员函数指针变量 的类型重定义
typedef void(TC:: * pFunc1)(int);
pFunc1 a = &(TC::normalFunc);
cout << "a = " << &a << endl;
pFunc1 v = &TC::normalVirtualFunc;
cout << "v = " << &v << endl;
TC tc;
(tc.*v)(20); //对象tc调用成员函数指针变量v所指向的成员函数。
}
void chengYuanBianLiangZhiZhen(){
//-- 普通成员变量指针
//int TC:: * a = &(TC::m_i); NG
int TC:: * a = &TC::m_i;
//-- a的首地址是0x00000004, 是该成员变量与该类对象首地址之间的偏移量,因为该类中有一个虚函数,虚函数的存在会伴随着一个虚函数表的存在,虚函数表正好占对象的 前四个字节。
TC tc;
//(tc.(*a)) = 8;
(tc.*a) = 8;
//-- 静态成员变量
int * pa = &TC::ms_i;
//-- pa指向的是一个真正的内存地址(而不是与该类对象 首地址之间的偏移量)
}
int TC::ms_i = 22;
int _tmain(int argc, _TCHAR* argv[])
{
chengYuanHanShuZhiZhen();
chengYuanBianLiangZhiZhen();
return 0;
}
C++基础成员函数指针与成员变量指针
最新推荐文章于 2023-02-01 15:03:30 发布