内容へ移動
C++プログラマのためのC++/CLI入門
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
以前のリビジョン
バックリンク
最近の変更
メディアマネージャー
サイトマップ
ログイン
>
最近の変更
メディアマネージャー
サイトマップ
現在位置:
TOP
»
cli
»
property
cli:property
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
{{indexmenu_n>17}} ====== property ====== C++で、あるprivateなメンバ変数に対して、読み取り用関数のみ提供したい場合は以下のように書くと思います。 <code cpp> class C { int length; public: C() : length(100) {} int getLength() const { return length; } }; int main() { C c; int len = c.getLength(); return 0; } </code> C++/CLIではプロパティを使って以下のようにかけます。 <code cpp> ref class C { int length; public: C() : length(100) {} property int Length { int get() { return length; } } }; int main() { C c; int len = c.Length; return 0; } </code> 次に値を設定したい場合を考えます。値の設定範囲として0から100までとし、それ以外の値の場合は無視するとします。C++では以下のようになります。 <code cpp> class C { int length; public: C() : length(100) {} int getLength() const { return length; } void setLength(int len) { if ( 0 <= len && len <= 100 ) length = len; } }; int main() { C c; c.setLength(50); return 0; } </code> propertyを使うと以下のようになります。 <code cpp> ref class C { int length; public: C() : length(100) {} property int Length { int get() { return length; } void set(int value) { if ( 0 <= value && value <= 100 ) length = value; } } }; int main() { C c; c.Length = 50; return 0; } </code> また上記の例で、宣言と実装を分けて書くと以下のようになります。 <code cpp> ref class C { int length; public: C() : length(100) {} property int Length { int get(); void set(int value); } }; int C::Length::get() { return length; } void C::Length::set(int value) { if ( 0 <= value && value <= 100 ) length = value; } int main() { C c; c.Length = 50; return 0; } </code> アクセス指定子をgetとsetで別々に書くこともできます。 <code cpp> public ref class C { int length; public: C() : length(100) {} property int Length { public: int get(); internal: void set(int value); } }; </code> ===== Trivial Property ===== get()やset()を明示的に書かなくても、コンパイラが勝手に作ってくれます。 <code cpp> public ref class C { public: property int Length; }; </code>
/var/www/html/virtual/cppcli/data/pages/cli/property.txt
· 最終更新: 2013/12/23 09:08 (外部編集)
ページ用ツール
文書の表示
以前のリビジョン
バックリンク
文書の先頭へ