2015-10-26 50 views
1

我想在我的代碼中的二進制文本數組作爲文字。這些消息非常小,所以我認爲使用'二進制'文字最容易。但怎麼做呢?如何創建一個二進制文字數組

我試過這段代碼:

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] 

我該如何解決這個問題?

UPDATE

我想你的意思是這樣的嗎?

#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

二進制文字是C++ 14的實際東西,看起來像'0b100110' - 如果這不是你的意思,你應該澄清你想要做什麼。 – melak47

+0

您正在使用十進制文字(如「3」)和十六進制文字(如「0x3」)的組合。但是,無論您將這些整數值表示爲十進制,十六進制,八進制還是二進制等,它們仍然只是編譯器的編號。在運行時沒有與該表示相對應的優化。 –

+0

使用'const',你可以做一些像'「\ x01 \ x02 \ x03」' – Jarod42

回答

1

如果你想使用初始化列表構造你的對象,你需要一個初始化列表構造函數。您當前的構造函數接受緩衝區和緩衝區的大小,但{ 3, { 0x1, 0x2, 0x3 } }就是這樣 - 它是數字和初始化程序列表的初始化程序列表。

要正確使用初始化列表,你的類和構造應該尋找大致如下:

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

而且你不會用size在所有 - 向量的大小會告訴你。

相關問題