Cpp クラス const 新しいページはコチラ
提供: yonewiki
(→クラス const) |
(→クラス const) |
||
| 36行: | 36行: | ||
それではクラスにおけるconstにはどのようなものがあるのか見てみましょう。 | それではクラスにおけるconstにはどのようなものがあるのか見てみましょう。 | ||
| + | |||
| + | |||
| + | クラスにおけるconstのだいたいのことがわかるサンプルを作ってみました。 | ||
| + | |||
| + | |||
| + | CConst001.h | ||
| + | <syntaxhighlight lang="cpp" line start="1"> | ||
| + | #pragma once | ||
| + | class CConst001 | ||
| + | { | ||
| + | private: | ||
| + | const int m_constnValue; | ||
| + | const int m_constnValue2; | ||
| + | int m_nValue; | ||
| + | public: | ||
| + | const int mpub_constnValue; | ||
| + | |||
| + | void mfpub_Set_m_nValue(int nPara1); | ||
| + | void mfpub_Set_m_nValueConstPara(int nPara1); | ||
| + | int mfpub_Get_m_nValue(); | ||
| + | int mfpub_Get_m_nValue() const; | ||
| + | int mfpubconst_Get_m_nValue() const; | ||
| + | |||
| + | CConst001(void); | ||
| + | ~CConst001(void); | ||
| + | }; | ||
| + | |||
| + | </syntaxhighlight> | ||
| + | CConst001.cpp | ||
| + | <syntaxhighlight lang="cpp" line start="1"> | ||
| + | #include "stdafx.h" | ||
| + | #include "Const001.h" | ||
| + | |||
| + | void CConst001::mfpub_Set_m_nValue(int nPara1){ | ||
| + | nPara1 = mpub_constnValue; | ||
| + | m_nValue = 1000; | ||
| + | printf("mfpub_Set_m_nValue\n", mpub_constnValue); | ||
| + | printf("m_nValue =%d\n", m_nValue); | ||
| + | printf("mpub_constnValue=%d\n", mpub_constnValue); | ||
| + | } | ||
| + | |||
| + | void CConst001::mfpub_Set_m_nValueConstPara(const int nPara1){ | ||
| + | //nPara1 = mpub_nValue;★const付きの引数は関数内で変更できない。 | ||
| + | m_nValue = 1000; | ||
| + | printf("mfpub_Set_m_nValueConstPara\n", mpub_constnValue); | ||
| + | printf("m_nValue =%d\n", m_nValue); | ||
| + | printf("mpub_constnValue=%d\n", mpub_constnValue); | ||
| + | } | ||
| + | |||
| + | //★const付きのオブジェクトからは呼び出し不可能な関数 | ||
| + | int CConst001::mfpub_Get_m_nValue(){ | ||
| + | m_nValue = 10; | ||
| + | return m_nValue; | ||
| + | } | ||
| + | |||
| + | //★const付きのオブジェクトからも呼び出し可能な関数 constメンバ関数 | ||
| + | int CConst001::mfpubconst_Get_m_nValue() const{ | ||
| + | //mpub_nValue = 10;★constメンバ関数ではメンバ変数の変更は出来ない。 | ||
| + | return m_nValue; | ||
| + | } | ||
| + | |||
| + | |||
| + | //★constメンバ関数はオーバーロードできます。 | ||
| + | int CConst001::mfpub_Get_m_nValue() const{ | ||
| + | //mpub_nValue = 10;★constメンバ関数ではメンバ変数の変更は出来ない。 | ||
| + | return m_nValue; | ||
| + | } | ||
| + | |||
| + | |||
| + | CConst001::CConst001(void):mpub_constnValue(0),m_constnValue(0),m_constnValue2(0)//★constメンバ変数の初期化 const以外も初期化できる。 | ||
| + | { | ||
| + | //mpub_constnValue = 100;★コンストラクタでもconstメンバ変数への代入はできない。 | ||
| + | } | ||
| + | |||
| + | |||
| + | CConst001::~CConst001(void) | ||
| + | { | ||
| + | } | ||
| + | |||
| + | </syntaxhighlight> | ||