ライブラリからヘッダー定義を見た
operator const wchar_t*() const
上記がキャスト演算子を定義した理由を誰かが私に説明できますか?
言語の構文です。C++ を使用すると、独自のものを作成できますOperators
例えば:
struct A {
bool operator==(const int i);
bool operator==(const char c);
bool operator==(const FOO& f);
}
これにより、より見栄えの良い構文である型を簡単に比較できます。別の方法は、のようなメソッドを全体にA a; if(a == 5) {}
実装することです。equals(int value)
A a; if(a.equals(5)) {}
キャストに関しても同様です。
struct Angle {
float angle;
operator const float() const {return angle;}
}
Angle theta;
float radius = 1.0f;
float x = radius*cos(theta);
float y = radius*sin(theta);
結論として、これは言語の優れた機能であり、コードの見栄えが良くなり、読みやすくなります。
たとえば、オブジェクトを にキャストする場合wchar_t *
、この演算子が提供されます。
例えば
MyString a("hello"); // is a string hold ansi strings. but you want change into wide chars.
wchar* w = (wchar_t*)a; // will invoke the operator~
フォームのメンバー関数はすべてoperator typename()
変換関数です。
const wchar_t*
は型名なのでoperator const wchar_t*()
、変換関数です。