0xfeeefeee错误
本帖最后由 Sj中国智造 于 2018-6-9 12:19 编辑#include <iostream>
#include <fstream>
#include <map>
using namespace std;
class ceshi
{
public:
map<int,int> obm;
int count;
};
int main()
{
ceshi c,c1;
c.count = 0;
c.obm = 10;
ofstream out("1.dat",ios::out|ios::binary);
out.write((char*)&c,sizeof(c));
out.close();
ifstream in("1.dat",ios::in|ios::binary);
in.read((char*)&c1,sizeof(c1));
cout <<c1.obm<<endl;
cout <<&(c1.obm)<<endl;
cout <<&(c.obm)<<endl;
in.close();
system("pause");
return 0;
}
简化版代码
求大神解啊,这是我们大作业中的一部分,可有偿,这个程序在vs2010收尾时不成功,在codeblocks下正常。急,求解决方法 #include <iostream>
#include <string>
int main()
{
std::string s1("1234");
std::string s2;
memcpy(&s2, &s1, sizeof(s1));
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
return 0;
}
你这个程序和我写的这个有什么区别? #include <iostream>
#include <string>
class String
{
public:
String()
{
this->data = NULL;
}
String(const char *s)
{
this->data = new char;
strcpy(this->data, s);
}
~String()
{
if(this->data)
delete[] this->data;
}
String &operator=(const String &r)
{
this->data = new char;
strcpy(this->data, r.data);
return *this;
}
friend std::ostream &operator<<(std::ostream &l, const String &r)
{
l << r.data;
return l;
}
private:
char *data;
};
int main()
{
String s1("1234");
String s2;
s2 = s1;
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
String s3("4567");
String s4;
memcpy(&s4, &s3, sizeof(String)); // 仔细想一想,这会发生什么问题?
std::cout << s3 << std::endl;
std::cout << s4 << std::endl;
return 0;
}
cpp的fstream并没有足够智能到足以保存类对象的的地步,所以你要么自己实现,要么借助第三方类库,下面我帮你写个一个比较简单的方法,你拿去吧
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
class ceshi{
public:
map<int, string> obm;
int count;
friend ifstream& operator>>(ifstream& is, ceshi& st);
friend ofstream& operator<<(ofstream& os, const ceshi& st);
};
ifstream& operator>>(ifstream& is, ceshi& st){
is >> st.count;
//如果map对象有多个的话,这里可以写个循环来循环写入
int first;
string second;
is >> first;
is >> second;
st.obm.insert(pair<int, string>(first, second));
return is;
}
ofstream& operator<<(ofstream& os, ceshi& st){
os << st.count << " ";
for (auto iter = st.obm.begin(); iter != st.obm.end(); iter++) {
os << iter->first << " " << iter->second << " ";
}
return os;
}
int main() {
ceshi c;
c.count = 6;
c.obm = "gdagzsd";
ofstream fout("ceshi.txt");
fout << c;
fout.close();
ceshi c2;
ifstream fin("ceshi.txt");
fin >> c2;
cout << c2.count << endl;
for (auto iter = c2.obm.begin(); iter != c2.obm.end(); iter++){
cout << iter->first << " " << iter->second << endl;
}
fin.close();
return 0;
}
页:
[1]