无法将结构向量转换为字符*
Can't cast vector of struct to char*
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。
演示。
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错