【发布时间】:2013-05-27 01:28:06
【问题描述】:
如果有人问了这个问题,我深表歉意。
我知道“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
我想听听你们的cmets关于我的声明:
- CObList 或 CPtrList 不能满足我的要求,对吗?
-
我的第一个想法是使用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
}
-
但是,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) } 其实,对于上面的场景,我其实想要一个“神奇”的列表。如果一个指针(非常量指针)被添加到这个“魔术”列表中,那么稍后从列表中检索指针将是一个“常量指针”,不能使用该指针来改变指向对象的内容。
问题:如何定义“魔法”列表?
【问题讨论】:
标签: c++ list pointers mfc constants