我想使用 CList
MFC 类的静态值和动态值。
我猜 &d1
是指向 d1
的指针值,所以不应该有错误,但是有。
我知道错误来自 const
之间的差异或不是,它不可能是左值。但我想将它用作 CList<DATA*, DATA*&>
的条目.
错误:
error C2664: 'struct __POSITION *__thiscall CList<struct DATA *,struct DATA
* &>::AddTail(struct DATA *& )' : cannot convert parameter 1 from 'struct
DATA *' to 'struct DATA *& '
然后我可以像下面这样简单地展示它。 还有另一种方法可以避免此错误吗? 提前致谢。
#include "stdafx.h"
#include <afxtempl.h>
struct DATA
{
int n;
CString id;
CString time;
};
DATA d1;
int main()
{
CList<DATA*, DATA*&> list2;
d1.n = 1;
//error here
list2.AddTail((DATA*)&d1);
//no error
DATA* pd1;
pd1 = &d1;
list2.AddTail(pd1);
return 1;
}
最佳答案
struct DATA { int n; CString id; CString time; }; ... CList<DATA*, DATA*&> list2;
我认为您正在使用 CList
错误的。您可能应该做的是:
CList<DATA> myList;
// Create and populate your data...
DATA d1;
d1.n = 1;
...
// Add new node to the list
myList.AddTail(d1);
注意更简单的语法 CList<DATA>
.链表由嵌入 DATA
的节点组成对象。为什么您需要另一个间接寻址,节点包含指向 DATA
的指针对象?这对缓存不太友好(跟随那些指向的数据)并且效率更低。
另请注意,如果您只是使用 CList<DATA>
, 第二个模板参数 ARG_TYPE
被正确推断为 const DATA&
默认情况下,根据 CList
模板声明(TYPE = DATA
,ARG_TYPE = const DATA&
):
template<class TYPE, class ARG_TYPE = const TYPE&> class CList : public CObject
编辑
如果您真的想将指针存储到DATA
在你的CList
节点,那么你可以这样做:
CList<DATA*> myPtrList;
DATA d1;
d1.n = 1;
...
myPtrList.AddTail(&d1);
关于c++ - MFC 错误如 A reference that is not to 'const' cannot be bound to a non-lvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45508220/