C++を思い出す・・・#6
メンバ関数ポインタ、メンバ変数ポインタを記述する際のシンタックスを忘れているのでメモメモ。
struct X{ const unsigned int x=999; const unsigned int f()const noexcept{return x;} }; int main() { { const unsigned int (X::*ptr_f)()const noexcept=&X::f; X x; std::cout<<(x.*ptr_f)()<<std::endl; std::cout<<(X().*ptr_f)()<<std::endl; } { const unsigned int X::*ptr_d=&X::x; X x; std::cout<<x.*ptr_d<<std::endl; std::cout<<X().*ptr_d<<std::endl; } }
constやnoexceptなどをメンバ関数に指定する際には、その変数ポインタの宣言、定義時にもそれらの指定内容を記述しなければならないできるのは、正直初めて知った。あまり使う機会がないものこそ、忘れやすいのでしっかりと頭に入れておきたいところである。
備忘録として、メンバ関数ポインタの配列みたいなものを書いたのでメモ。
struct X{ auto f()noexcept{return x;} auto g()noexcept{return x+1;} auto h()noexcept{return x+2;} private: const unsigned int x=10; }; int main() { unsigned int (X::*ptr[])()={&X::f,&X::g,&X::h}; X x; for(auto&& i:ptr)std::cout<<(x.*i)()<<std::endl; // 10,11,12 }
追記
念には念を...ここ二日間のシャローコピーの内容と本エントリの内容をまとめたテストコードを記述した。忘れませんように。
struct X{ X()=default; X(const X& src_obj) { *p=*src_obj.p; } X& operator=(const X& src_obj) { *p=*src_obj.p; return *this; } X(X&&)=delete; X& operator=(X&&)=delete; void show(){std::cout<<*p<<std::endl;} void set_value(unsigned int i){a=i;} private: unsigned int a=10; unsigned int* p=&a; }; int main() { X x,y; void (X::*ptr_f_0)()=&X::show; void (X::*ptr_f_1)(unsigned int)=&X::set_value; (x.*ptr_f_0)(); y.set_value(999); (y.*ptr_f_0)(); x=y; (x.*ptr_f_0)(); }
...まあ、意味的に理解したので、忘れるも何も、考えばかけるとは思うが。