【问题标题】:Require Help Resolving error C2664需要帮助解决错误 C2664
【发布时间】:2015-03-12 02:27:54
【问题描述】:

我有以下代码给我这个错误

main.cpp(41): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : 无法将参数 1 从 'Handle' 转换为 'unsigned int &'

我的示例程序是

#include <vector>
#include <utility>
typedef unsigned int u32;
typedef u32 Handle;

struct File
{
    File()
        : ch(0),
        pageIdx(0)
    {
    }
    Handle ch : 8;
    u32 pageIdx;
};

int main() {
    std::vector<std::pair<Handle, u32> > toTrim;
    toTrim.reserve(64);
    File* m_pFirstPage = new File();
    File* pRef = m_pFirstPage;
    toTrim.push_back(std::make_pair(pRef->ch,pRef->pageIdx));
    return 0;
}

当我尝试静态转换时,即

toTrim.push_back(std::make_pair(static_cast<unsigned int>(pRef->ch), pRef->pageIdx));

我收到以下错误

main.cpp(41): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : 无法将参数 1 从 'unsigned int' 转换为 'unsigned int &'

谁能帮我解决它并解释我做错了什么。

【问题讨论】:

  • 我认为它不喜欢位域。如果这是你想要的,为什么不使用 8 位整数呢?还有为什么要动态分配文件对象?
  • 删除了我的答案,因为我认为这可能是编译器问题,您的 static_cast 版本在 GCC 5 上对我来说可以正常工作,您使用的是什么编译器?
  • 对于错误符号“C2664”我会说 VC++
  • 我在 Microsoft Visual Studio Professional 2013 上运行代码
  • 你需要“:8”符号吗?没有它,它可以正确编译

标签: c++ pointers casting


【解决方案1】:

发生的情况是您使用 : 8 表示法指定位字段。

更多信息请访问: http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

这会在您的句柄变量上创建一个 8 位的伪字符字段,而不是 typedef u32 Handle 定义的 32 位。 std::make_pair 需要通过引用传递它的参数。

由于Handle ch : 8Handle 的类型不同,因此您不能通过引用传递它,因为将通过引用传递的变量视为未定义行为。

更多信息请访问: How to cast a variable member to pass it as reference argument of a function

如果您需要 : 8 字段,您可以使用额外的变量来正确创建对。

#include <vector>
#include <utility>
typedef unsigned int u32;
typedef u32 Handle;

struct File
{
    File()
    : ch(0),
    pageIdx(0)
    {
    }
    Handle ch : 8; //Different type than just Handle
    u32 pageIdx;
};

int main() {
    std::vector<std::pair<Handle, u32> > toTrim;
    toTrim.reserve(64);
    File* m_pFirstPage = new File();
    File* pRef = m_pFirstPage;
    unsigned int ch_tmp = pRef->ch; //<-Extra variable here
    toTrim.push_back(std::make_pair(ch_tmp, pRef->pageIdx));
    return 0;
}

【讨论】:

  • 非常感谢关于删除 :8 的解释,代码可以编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2021-09-10
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多