指针的使用和练习 I - 如何通过指针访问的使用对象里的private信息

指针与int类型的自由转换

 

// TonnyPtr.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <Windows.h>


class testclass
{
public:
 testclass();
 ~testclass();

 virtual void add2num(int a, int b);

private:

 virtual void WINAPI pri_add2num(int a, int b, int c);

private:

 int addsum;
};

testclass::testclass(){}

testclass::~testclass(){}

void testclass::add2num(int a, int b)
{
 addsum = 0;

 addsum = a + b;

}

void testclass::pri_add2num(int a, int b, int c)
{
 int total = 0;
 
 total = a + b + c + addsum;

 addsum = total;

 return;
}


typedef void (WINAPI *pfunadd)(void* pthis, int a, int b, int c);

int _tmain(int argc, _TCHAR* argv[])
{
 int _int_a = 100; // define a int variable with value.

 _int_a = (int) &_int_a; // 取得 _int_a 的地址,作为 _int_a 的值

 int* _int_pa = &_int_a; // 定义一个指针,指向 _int_a.

 int _int_b = *_int_pa; // 指针取值,并赋值为 _int_b. 值为 _int_a 的地址 也是_int_a的值

 

 int _int_c = 10; // 定义一个 int c 变量

 int _int_d = (int)&_int_c; // 定义另一 int d变量 用来存储 int c的地址

 int* _int_pc = (int*)*(int*)(&_int_d); // 强制转化为 int 指针,并 赋值为另一个 int指针

 int _int_e = *_int_pc; // 指针 pc 的值 赋值为另一个 int e 变量. int e 应该等于 int c

 
 // 对象,私有变量操作

 testclass _tc_a; // 定义一个 testclass 对象

 _tc_a.add2num(1, 2); // 调用 _tc_a 的公共方法 给私有变量 addsum 赋值. addsum = 3

 int* _tc_pa = (int*)(&_tc_a); // 取 _tc_a 的地址,赋值为 int指针 _tc_pa.

 _tc_pa++; // 移动 int 指针,指向 _tc_a 对象的私有变量

 *_tc_pa *= 2; // _tc_a 对象的私有变量 addsum * 2, addsum = 6;


 // 对象,私有方法操作

 pfunadd _tc_pafun = (pfunadd)*(((int*)(*(int*)(&_tc_a))) + 1); // pfunadd _tc_pafun = (pfunadd)*((int*)*(int*)(&_tc_a) + 1);

  _tc_pafun(&_tc_a, 3,4,5); // 预期 addsum = 18;

 return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值