c++ - MFC 错误如 A reference that is not to 'const' cannot be bound to a non-lvalue

标签 c++ templates linked-list mfc

我想使用 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 = DATAARG_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/

相关文章:

c++ - 从原始 xml 创建 xml 文件的子集,同时保持相同的结构

c++ - 在单独的文件中定义的类

javascript - Kendo DropDownList 条件 if else 模板

c - C删除链表中的第一个节点

java - 从 LinkedList 中删除特定元素....?

c - 在 C 中搜索链表

C++ 忽略 if 语句条件

c++ - 用 C 重写 C++ 类

c++ - 在调度表中的类外使用模板类方法

python - 当基本模板位于根文件夹中时 TemplateDoesNotExist