c++ - 如何创建二进制文字数组

标签 c++

我希望我的代码中的二进制消息数组作为文字。消息非常小,所以我认为使用“二进制”字面量是最简单的。但是要怎么做呢?

我试过这段代码:

struct binary_message
{
    binary_message(int size, unsigned char* bytes) : size_(size), bytes_(bytes) {}
    int size_;
    unsigned char* bytes_;
};

binary_message messages[] = {
    { 3, { 0x1, 0x2, 0x3 } },
    { 2, { 0x1, 0x2 } },
    { 1, { 0x1 } }
};

使用 Visual Studio 2013 C++ 编译器时出现错误:

error C2440: 'initializing' : cannot convert from 'initializer-list' to 'binary_message'. No constructor could take the source type, or constructor overload resolution was ambiguous

使用 g++ 我得到:

>g++ main.cpp
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: error: could not convert '{3, {1, 2, 3}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: could not convert '{2, {1, 2}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: invalid conversion from 'int' to 'unsigned char*' [-fpermissive]
main.cpp:4:2: error:   initializing argument 2 of 'binary_message::binary_message(int, unsigned char*)' [-fpermissive]

如果我使用 g++ -std=c++0x main.cpp 我仍然得到:

main.cpp:13:1: error: could not convert '{3, {1, 2, 3}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: could not convert '{2, {1, 2}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: invalid conversion from 'int' to 'unsigned char*' [-fpermissive]
main.cpp:4:2: error:   initializing argument 2 of 'binary_message::binary_message(int, unsigned char*)' [-fpermissive]

我该如何解决这个问题?

更新

我猜你的意思是这样的?

#include <vector>
#include <iostream>

struct binary_message
{
    binary_message(std::initializer_list<unsigned char> data) : bytes_(data) {}
    std::vector<unsigned char> bytes_;
};

int main()
{
    binary_message messages[] = {
            { 0x1, 0x2, 0x3 },
            { 0x1, 0x2 },
            { 0x1 }
    };

    binary_message msg1 = messages[0];

    return 0;
}

最佳答案

如果你想使用初始化列表来构造你的对象,你需要一个初始化列表构造函数。您当前的构造函数接受缓冲区的大小和缓冲区,但 { 3, { 0x1, 0x2, 0x3 } } 与此完全不同 - 它是一个数字和初始化列表的初始化列表。

要正确使用初始化列表,您的类和构造函数应该大致如下所示:

binary_message( std::initializer_list<int> data) : data(data) {}
...
std::vector<int> data;

而且您根本不会使用 size - vector 的大小会告诉您。

关于c++ - 如何创建二进制文字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33352404/

相关文章:

c++ - 在自建android中包含C++共享库。启动 ndk-build 时出错

c++ - 阵列访问期间的段错误

c++ - 我怎么可能从一个还没有定义一些成员方法的类中创建一个实例呢? (C++)

c++ - std::queue front 会将前面的元素移出行外吗?

c++ - CImg.h无法在Xcode环境中运行

c++ - 错误时会发生什么 - Bison

c++ - Qt - 从 C++ 线程发出信号

c++ - SQLite 预更新 Hook 重入

c++ - 我如何从WAV文件中获取时域频率?

c++ - 将 Lua 嵌入到与 C 混合的 C++ 中