2013-05-27 92 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