所以我需要有一个静态数字来计算对象的数量,然后将其分配给id。然后,我需要使该id唯一,以便即使在我关闭应用程序并再次打开它时也无法再次使用它。我怎么做?
piggyBank.cpp
int PiggyBank::nrOfObjects = 0; // outside constructor
PiggyBank::getNrOfObjects(){
return nrOfObjects;
}
PiggyBank::PiggyBank(void){
{this->owner="";this->balance=0;this->broken=false;}
id = ++nrOfObjects;
}
PiggyBank::PiggyBank(std::string name){
{ this->owner=name;this->balance=0;this->broken=false; }
id = ++nrOfObjects;
}
PiggyBank::PiggyBank(std::string name, int startBalance){
{this->owner=name;this->balance=startBalance;this->broken=false;}
id = ++nrOfObjects;
}
piggyBank.h
private:
std::string owner; // PiggyBank owner
int balance; // Current balance in PiggyBank
bool broken; // true if PiggyBank is broken, else false
int id;
static int nrOfObjects;
public:
PiggyBank(void);
PiggyBank(std::string name);
PiggyBank(std::string name, int startBalance);
static int getNrOfObjects();
答案 0 :(得分:1)
您可以使用fstream
来写入文件,并使用ifstream
来读取文件。
例如:
#include <fstream>
using namespace std;
要写入文件:
fstream out_file {filename,ios::out | ios::binary);}; //create file
out_file.write((char*)&pointerToObject, sizeof(obj)); //write data to file
out_file.close(); //close the file
为了读取文件:
ifstream ifile;
ifile.open(filename, ios::in | ios::binary); //open file
ifile.seekg (0, ifile.end);
ifile length = ifile.tellg(); //get file length
ifile.seekg (0, ifile.beg);
char * buffer = new char [length]; //create buffer
ifile.read(buffer,length); //read from file to buffer
ifile.close(); //close file
delete[] buffer;