-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 *にキャストしたいので、ファイルに書き込めます。この例はなぜ機能しないのですか?私は、次のエラーを取得しています:structのベクトルを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);
^
はEDIT:
今、私がファイルに複雑な構造体のベクトルを読み書きする方法の作業例を持っています。
#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;
}
C++はちょうどここでスマートです。それは 'char *'にキャストするのは意味がありません。結果をファイルに書くと想像するように動作しません。 – Hayt
あなたは何をしたいのか分かりません。 'reinterpret_cast(&testArray.front())'がほしいかもしれません。 –
songyuanyao
'reinterpret_cast'に構文エラーがありませんか?私。あなたは '.front())'で早すぎる呼び出しを閉じます。 – pingul