我希望代码中的二进制消息数组为文字。消息非常小,所以我认为使用'二进制'文字最容易。但是怎么做呢?
我试过这段代码:
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;
}
答案 0 :(得分:1)
如果要使用初始化列表构建对象,则需要初始化列表构造函数。您当前的构造函数接受缓冲区和缓冲区的大小,但{ 3, { 0x1, 0x2, 0x3 } }
不是那样的 - 它是数字和初始化列表的初始化列表。
要正确使用初始化程序列表,您的类和构造函数应该大致如下:
binary_message( std::initializer_list<int> data) : data(data) {}
...
std::vector<int> data;
你根本不会使用size
- 矢量的大小会告诉你。