无法将结构向量转换为字符*

Can't cast vector of struct to char*

本文关键字:字符 转换 向量 结构      更新时间:2023-10-16
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*,这样我就可以写入文件。为什么这个例子不起作用呢?我得到以下错误:

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;
}

front()返回对vector的第一个元素的const引用,因此其类型为struct test。如果没有自定义类型转换操作符,则不能将struct强制转换为指针。

可以取front()data()const指针,也可以取begin()的解引用地址:

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

取消对begin()的引用可以避免转换const -ness。

演示。