1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include "stdio.h" #include "stddef.h" class A { int i; class B { B(){ }; public: void bfunc() { //ここでA::iにアクセスする方法ありますか? B* pB = this; size_t ofs = offsetof(A, A::b); A* pA = (A*)( (reinterpret_cast<const volatile char*>(this))-offsetof(A,A::b)); pA->i = 200; } friend class A; }; public: A(){ i = 100; }; void printa() { printf("%d", i); } B b; friend class B; }; int main(int argc, char* argv[]) { A a; a.b.bfunc(); a.printa(); return 0; } |
g++でコンパイル
1 2 3 4 5 6 7 8 9 |
$ g++ test.cpp test.cpp: In member function ‘void A::B::bfunc()’: test.cpp:14: warning: invalid access to non-static data member ‘A::b’ of NULL object test.cpp:14: warning: (perhaps the ‘offsetof’ macro was used incorrectly) test.cpp:15: warning: invalid access to non-static data member ‘A::b’ of NULL object test.cpp:15: warning: (perhaps the ‘offsetof’ macro was used incorrectly) $ ./a.out 200 $ |
なんか色々出たがスルー。
reinterpret_castを使っているのはAがキャスト演算子を持ってたらやばいためと思われる。またこれはthisがNULLかどうかのチェックはしてないがスルー。