この質問がされている場合は、お詫び申し上げます。
「const ポインター」と「const へのポインター」の意味と構文の違いを認識しています。
char * const myPtr; は「const ポインター」であり、「myPtr = &char_B;」として使用することはできません。
const char * myPtr; は「const へのポインター」であり、「*myPtr = 'J';」として使用することはできません。
MFC のコンテナーを使用している場合、http://msdn.microsoft.com/en-us/library/fw2702d6%28v=vs.71%29.aspx
私の声明に対するあなたのコメントを聞きたいです。
- CObList または CPtrList は私の要件を満たすことができませんよね?
私の最初の考えは、たとえば、CTypedPtrList を使用することです。
CTypedPtrList は、"const ポインター" であるメンバーを持つリストを意味します。
これは実際には機能しますが、「役に立たない」:
class CAge
{
public:
int m_years;
CAge( int age ) { m_years = age; }
};
CTypedPtrList<CPtrList, CAge* const> list;
list.AddTail(new CAge(10));
list.AddTail(new CAge(5));
POSITION pos = list.GetHeadPosition();
while(pos)
{
CAge* a = (CAge*)list.GetNext(pos);
a = new CAge(11); //That's why I say it is "useless", because the returned value can be assigned
list.GetNext(pos) = new CAge(11); //Expected, can not pass compile
}
ただし、CTypedPtrList は機能していません。「const へのポインター」メンバーなどのリストが必要です。
CTypedPtrList<CPtrList, const CAge*> list2; //list2.AddTail(new CAge(10)); //Help! This does not pass compile, then how to initialize list2??? //list2.AddTail(new CAge(5)); POSITION pos2 = list2.GetHeadPosition(); while(pos2) { CAge* a = (CAge*)list2.GetNext(pos2); a->m_years = 50; //This passed compile. That's why I say "MORE". //((CAge*)list2.GetNext(pos2))->m_years = 50; //This passed compile (because of type cast) //((const CAge*)list2.GetNext(pos2))->m_years = 50; //this does not pass compile (because of type cast as well) }
実際、上記のシナリオでは、実際には「魔法の」リストが必要です。ポインター (非定数ポインター) がこの「マジック」リストに追加された場合、後でリストからのポインターの取得は「定数ポインター」になり、ポインターを使用してポイントされたオブジェクトの内容を変更することはできません。
質問:「魔法の」リストを定義する方法は?