0
点赞
收藏
分享

微信扫一扫

C++ 包裹下 void * 空指针类型

可以用结构体包裹下,做下标识。

#include <iostream>
#include <string>
#include<cassert>

using namespace std;

struct VoidType
{
string Type;
void* pVoid;

VoidType(string typeStr, void* p_void) :Type(typeStr), pVoid(p_void) {}
};


bool ChangeValueTo100(VoidType* vt)
{
//assert(vt->Type == "int");
if (vt->Type != "int") {
return false;
}
int* pVoid = (int*)(vt->pVoid);
*pVoid = 100;

return true;
}


int main()
{
int test = 199;

VoidType v("int", &test);
ChangeValueTo100(&v);

std::cout << "test = " << test << std::endl;

return 0;
}

输出:

test = 100

在 release 模式下用 assert

#undef NDEBUG
#include<cassert>



举报

相关推荐

0 条评论