【发布时间】:2010-11-23 06:17:05
【问题描述】:
我想将一个项目写入一个二进制文件,关闭它,然后再次打开它以读取它。代码简单明了,使用 Visual Studio 2008 编译和运行没有错误。
但是,使用 GCC 编译器运行时出现“段错误”。
我做错了什么?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Item
{
private:
string itemID;
string itemName;
string itemState;
public:
Item( const string& id = "i0000", const string& name = "Zero item", const string& state = "not init" )
: itemID( id ) , itemName( name ) , itemState( state )
{
}
string& operator []( int x )
{
if ( 0 == x )
return itemID;
if ( 1 == x )
return itemName;
if ( 2 == x )
return itemState;
return ( string& )"";
}
const string& operator []( int x ) const
{
if ( 0 == x )
return itemID;
if ( 1 == x )
return itemName;
if ( 2 == x )
return itemState;
return ( string& )"";
}
public:
friend istream& operator >>( istream& i, Item& rhs )
{
cout << " * ItemID: ";
getline( i, rhs.itemID );
cout << " - Item Name: ";
getline( i, rhs.itemName );
cout << " - Item State: ";
getline( i, rhs.itemState );
return i;
}
friend ostream& operator <<( ostream& o, const Item& rhs )
{
return o << "ID = " << rhs.itemID
<< "\nName = " << rhs.itemName
<< "\nState = " << rhs.itemState << endl;
}
};
void write_to_file( const string& fn, const Item& item )
{
fstream outf( fn.c_str(), ios::binary | ios::out );
Item temp( item );
outf.write( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
outf.close();
}
void read_from_file( const string& fn, Item& item )
{
fstream inf( fn.c_str(), ios::binary | ios::in );
if( !inf )
{
cout << "What's wrong?";
}
Item temp;
inf.read( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
item = temp;
inf.close();
}
int main()
{
string fn = "a.out";
//Item it( "12", "Ipad", "Good" );
//write_to_file( fn, it );
Item temp;
read_from_file( fn, temp );
cout << temp;
return 0;
}
【问题讨论】:
-
这与你的问题无关,但是两个
operator[]函数中的两行return ( string& )""是未定义的行为。您正在(隐式)在 return 语句中构造一个临时的std::string对象,然后返回对该临时对象的引用,这是一个很大的禁忌。您应该改为返回对静态/全局对象的引用,或者更好的是,引发断言或抛出异常。 -
非常感谢亚当。我现在明白我的问题了。
标签: c++