2013-05-27 90 views
0

如果已經提出這個問題,我表示歉意。C++:作爲成員的「const指針」列表VS與作爲成員的「指向const的指針」列表

我知道「const指針」與「指向const的指針」之間的含義和語法區別。

char * const myPtr;是「常量指針」,不能用作「myPtr = & char_B;」

const char * myPtr;是「指向const的指針」,不能用作「* myPtr ='J';」

如果我使用MFC的容器,http://msdn.microsoft.com/en-us/library/fw2702d6%28v=vs.71%29.aspx

我想聽取你們對我的聲明發表評論:

  1. CObList或CPtrList不能滿足我的要求,正確嗎?
  2. 我的第一個想法是使用CTypedPtrList的,例如:

    CTypedPtrList的意味着成員是「常量指針」的列表。

其實,這工作,但 「無用」:

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 
} 
  1. 然而,CTypedPtrList的不工作。我想要一個帶有「指向常量」成員和更多的列表。

    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) 
    } 
    
  2. 其實,對於上面的場景,我其實想要一個「魔術」列表。如果一個指針(非常量指針)被添加到這個「magic」列表中,那麼稍後從列表中檢索指針將是一個「常量指針」,不能使用指針來改變指向對象的內容。

問題:如何定義 「神奇」 名單?

回答

0

不可能強制新對象爲const。類型系統僅確保舊對象的引用/指針保持爲const

至於CAge* a = (CAge*)list2.GetNext(pos2);,只需刪除演員。 Casts會破壞類型系統(事實上這是強制轉換的關鍵),所以您不應該對它們允許您通過const參考路徑修改對象感到驚訝。

+0

謝謝!是的,如你所說,如果我使用「CAge * a = list2.GetNext(pos2);」那麼編譯器可以捕獲錯誤「error C2440:'initializing':can not convert from'const CAge *'to'CAge *'」;但是,如果我使用「CAge * a = list.GetNext(pos);」,我仍然可以調用「a = new CAge(11);」之後。這是否意味着我對容器中const指針的評論爲「無用」仍然存在? – milesma

+0

另一個問題,初始化包含「指向const」成員的列表的可能方法是什麼?你知道是否有方法來定義上一節中描述的這種「魔術」列表? – milesma