void*型からのキャストはstatic_castが推奨される。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// genericpointer.cpp | |
// CplusplusPractice | |
// | |
// Created by masai on 2015/05/19. | |
// Copyright (c) 2015年 masai. All rights reserved. | |
// | |
#include <iostream> | |
#include <typeinfo> | |
#include <cxxabi.h> | |
// 構造体Container | |
struct Container{ | |
void* data; | |
}; | |
// 構造体Num | |
struct Num{ | |
int n; | |
}; | |
int main(int argc, const char * argv[]) { | |
const char* text = "text"; | |
Container con1; | |
// Container構造体のdataにconst charのポインタを入れる(void*にキャストする) | |
con1.data = (void*)text; | |
std::cout << "con1.data = " << abi::__cxa_demangle(typeid(con1.data).name(), 0, 0, 0) << std::endl; | |
// Num構造体を動的確保 | |
Num* numPointer = new Num(); | |
numPointer->n = 42; | |
// Container構造体のdataにNum型のポインタを入れる | |
Container con2; | |
con2.data = (void*)numPointer; | |
std::cout << "con2.data = " << abi::__cxa_demangle(typeid(con1.data).name(), 0, 0, 0) << std::endl; | |
printf("%s\n", static_cast<const char*>(con1.data)); // 取り出す際にstatic_castする | |
printf("%d\n", ((Num*)con2.data)->n); //通常のキャストも可能 | |
return 0; | |
} |
0 件のコメント:
コメントを投稿