2016-10-11 27 views
-3
struct test{ 
    int x; 
    float y; 
    float array[100]; 
    test(){ 
     x = 0; 
     y = 1.0; 
     for(int i=0; i<100; i++){ 
      array[i] = i; 
     } 
    } 
    void print(){ 
     std::cout << x << " " << y << std::endl; 
     for(int i=0; i<100; i++){ 
      std::cout << i << " "; 
     } 
    } 
}; 

    std::vector<test> testArray; 
    testArray.push_back(test()); 

    reinterpret_cast<char*>(testArray.front()), 2 * sizeof(test); 

我想將testArray轉換爲char *,以便我可以寫入文件。爲什麼這個例子不起作用?我收到以下錯誤:無法將結構向量轉換爲char *

file.cpp:71: error: invalid cast from type '__gnu_cxx::__alloc_traits<std::allocator<test> >::value_type {aka test}' to type 'char*' 
    reinterpret_cast<char*>(testArray.front()), 2 * sizeof(test); 
              ^

編輯:

現在我對如何閱讀和編寫一個複雜的結構向量到文件的工作示例。

#include <vector> 
#include <fstream> 
struct MyStruct{ 
    int x; 
    float y; 
    float array[100]; 
    MyStruct(){ 
     x = 0; 
     y = 1.0; 
     for(int i=0; i<100; i++){ 
      array[i] = i; 
     } 
    } 
    void print(){ 
     std::cout << x << " " << y << std::endl; 
     for(int i=0; i<100; i++){ 
      std::cout << i << " "; 
     } 
    } 
}; 

template<typename T> 
void write_pod(std::ofstream& out, T& t) 
{ 
    out.write(reinterpret_cast<char*>(&t), sizeof(T)); 
} 

template<typename T> 
void read_pod(std::ifstream& in, T& t) 
{ 
    in.read(reinterpret_cast<char*>(&t), sizeof(T)); 
} 

template<typename T> 
void write_pod_vector(std::ofstream& out, std::vector<T>& vect) 
{ 
    long size = vect.size(); 
    write_pod<long>(out, size); 
    out.write(reinterpret_cast<char*>(&vect.front()), size * sizeof(T)); 
} 

template<typename T> 
void read_pod_vector(std::ifstream& in, std::vector<T>& vect) 
{ 
    long size; 
    read_pod(in, size); 
    vect.resize(size); 
    in.read(reinterpret_cast<char*>(&vect.front()), size * sizeof(T)); 
} 

int main(int argc, char **argv) 
{ 
    ros::init(argc, argv, "weighing_area"); 


    std::vector<MyStruct> testArray; 
    testArray.push_back(MyStruct()); 
    testArray.push_back(MyStruct()); 


    ofstream myfile("/home/me/TEST.dat"); 
    write_pod_vector<MyStruct>(myfile, testArray); 
    myfile.close(); 

    std::vector<MyStruct> readArray; 
    ifstream readfile("/home/me/TEST.dat"); 
    read_pod_vector(readfile, readArray); 

    cout << readArray.size() << endl; 
    for(int i=0; i<readArray.size(); i++){ 
     MyStruct& myStruct = readArray[i]; 
     myStruct.print(); 
    } 

    return 0; 
} 
+2

C++在這裏很聰明。把它轉換成char *是沒有意義的,如果你把結果寫到一個文件中,它就不會像你想象的那樣工作。 – Hayt

+0

我不確定你想做什麼;您可能需要'reinterpret_cast (&testArray.front())'。 – songyuanyao

+1

你的'reinterpret_cast'中沒有語法錯誤嗎?即您在'.front()'過早關閉了電話'' – pingul

回答

2

front()返回const參考vector的第一個元素,所以它的類型是struct test。缺少自定義類型轉換運算符,struct不能轉換爲指針。

您可以乘坐const指針front()data()的,或採取非關聯begin(),而不是地址:

auto x = reinterpret_cast<char*>(&(*testArray.begin())); 
cout << (void*)x << endl; 

提領begin()可以讓你避免擺脫了const -ness。

Demo.