Created
August 21, 2015 07:18
-
-
Save keisukefukuda/b3188b65ac335186be8e to your computer and use it in GitHub Desktop.
->* 演算子と .* 演算子の実験
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
#include <iostream> | |
struct Test { | |
int val; | |
// ->* 演算子は、任意の型についてオーバーロードできる | |
void operator->*(int i) { | |
std::cout << "operator->* is called with value " << i << std::endl; | |
} | |
}; | |
int main() { | |
Test t; | |
t.val = 100; | |
// Testクラスのvalメンバーへのポインタ(コンパイラの実装に依るが、実際の中身は相対アドレス) | |
int Test::*pval = &Test::val; | |
// .* 演算子を用いた、メンバーへのポインタを用いたメンバーへのアクセス | |
std::cout << t.*pval << std::endl; | |
// オーバーロードされた ->* 演算子の呼び出し | |
// ただし、演算子の右辺は何らかの値 or 変数でなければならない | |
// 「t->x の代わりに t->*x を使ってもらう」という方法をちょっと考えたが、 | |
// t->*x のようには書けない。 x が未定義識別子というエラーになる | |
// 下の式は動く | |
t->*3; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment