64,649
社区成员
发帖
与我相关
我的任务
分享
// MEMBER FUNCTIONS FOR _Container_base12
inline void _Container_base12::_Orphan_all()
{ // orphan all iterators
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != 0)
{ // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
*_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)
(*_Pnext)->_Myproxy = 0; // 报错的行
_Myproxy->_Myfirstiter = 0;
}
#endif /* _ITERATOR_DEBUG_LEVEL == 2 */
}
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Book
{
public:
string No;
string Name;
string Author;
double Price;
int Number;
Book()
{
cout << "构造Book对象" << endl;
}
Book(const Book &rhs)
{
this->No = rhs.No;
this->Name = rhs.Name;
this->Author = rhs.Author;
this->Price = rhs.Price;
this->Number= rhs.Number;
cout << "拷贝构造函数 " + this->Name << endl;
}
Book(string o,string n,string a,double p,int u)
:No(o),Name(n),Author(a),Price(p),Number(u)
{
cout << "构造 "+ n << endl;
}
~Book()
{
cout<<"析构 "<<Name<<endl;
}
friend ostream & operator<< (ostream &output,Book &s)
{
output << "编号: " << s.No << endl
<< "书名: " << s.Name<< endl
<< "作者: " << s.Author<< endl
<< "价格: ¥" << s.Price<< endl
<< "数量: " << s.Number<< endl;
return output;
}
friend istream & operator>> (istream &input,Book &s)
{
input >> s.No >> s.Name >> s.Author >> s.Price >> s.Number;
return input;
}
};
int main()
{
ifstream input,input2;
ofstream output,output2;
vector<Book> vb;
Book b1("AA-AABB","自然百科","yaoshuangqi",20.5,11);
Book b2("AA-ACBB","恐龙百科","chenerqian",20.5,17);
Book b3("XA-AABB","C++ Prime","Stanley B. Lippman",128.00,1);
Book b4("XA-AXBB","深入浅出C++","Lvxiaona",54.20,7);
Book b5("XA-AXFB","HTML","Lvxiaona",54.20,7);
vb.push_back(b1);
vb.push_back(b2);
vb.push_back(b3);
vb.push_back(b4);
vb.push_back(b5);
int x =0;
output2.open("2.txt",ios::binary);
if(output2.is_open())
{
for(auto it = vb.begin(); it != vb.end();++it)
{
output2.write((char *)&(*it),sizeof(*it));
//output2.flush();
x++;
}
output2.close();
}
// 按照类对象读取
int y=0;
input2.open("2.txt",ios::binary);
if(input2.is_open())
{
Book b ;
while(!input2.eof())
{
y++;
input2.read((char *)&b,sizeof(Book));
if(input2.rdstate()) break;
cout << b << endl;
}
input2.close();
}
// vector存放类对象的时候,释放vector内存 其实没有必要
vector<Book>(vb).swap(vb);
system("pause");
return 0;
}
public:
char No[20];
char Name[40];
char Author[40];
double Price;
int Number;
字符串需要确定的字符长度,否则读取的时候读取不到。