【问题标题】:Constructor error when initializing c++ vector with struct使用 struct 初始化 c++ 向量时出现构造函数错误
【发布时间】:2018-09-08 13:36:03
【问题描述】:

我正在尝试使用以下 2 个值初始化 struct opcodeTable 的向量:

struct opcodeTableE {
        uint16_t opcode;
        uint16_t mask;
        void (chipCpu::*instruction)(uint16_t);
};

std::vector<opcodeTableE> opcodetable{
        {0x00E0, 0xFFFF, chipCpu::clearScreen},
        {0x00EE, 0xFFFF, chipCpu::returnFromSub}
};

但我收到以下错误:

no instance of constructor "std::vector<_Tp, _Alloc>::vector [with _Tp=chipCpu::opcodeTableE, _Alloc=std::allocator<chipCpu::opcodeTableE>]" matches the argument list -- argument types are: ({...}, {...})

注意:我使用的是 C++14

【问题讨论】:

    标签: c++ vector struct c++14


    【解决方案1】:

    您需要使用operator&amp; 来获取指向成员函数的指针。例如

    std::vector<opcodeTableE> opcodetable{
            {0x00E0, 0xFFFF, &chipCpu::clearScreen},
            {0x00EE, 0xFFFF, &chipCpu::returnFromSub}
    };
    

    LIVE

    顺便说一句:operator&amp; 仅在获取指向非成员函数或静态成员函数的指针时是可选的,因为函数到指针的隐式转换。

    【讨论】:

    • 这是我做完之后得到的:error: could not convert '{{224, 65535, &amp;chipCpu::clearScreen}, {238, 65535, &amp;chipCpu::returnFromSub}}' from '&lt;brace-enclosed initializer list&gt;' to 'std::vector&lt;chipCpu::opcodeTableE&gt;'
    • @KnoxRoot 你能创建一个mcve 来重现错误吗?我尝试制作一个here,效果很好。
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2019-04-30
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多