2016-09-04 1 views
-5

скопируйте этот адрес (я не хочу копировать адрес), а затем я освобожу первый объект Все курсы Этот класс упражнений Я должен реализовать сохранение и загрузку игры Treasure HuntДвоичный файл-obj (игра) сохранить и загрузить obj

Мои файлы: Главная:

srand(time(0)); 
TreasureSeeker dudu; 
int save = 0; 
cout << "To New game prees 1 to load game prees 2 : "; 
cin >> save; 
while (save !=1 &&save !=2) 
{ 
    cout << "To New game prees 1 to load game prees 2 : "; 
    cin >> save; 
} 
if (save == 1) 
{ 
    ifstream inFile("try.dat", ios::binary); 
    TreasureSeeker temp(inFile); 
    inFile.close(); 
    temp.play(); 
} 
else 
{ 
    dudu.setname(); 
    dudu.play(); 
    ofstream outFile("try.dat", ios::binary | ios::trunc); 
    dudu.save(outFile); 
    outFile.close(); 
} 

и ':

#define _CRT_SECURE_NO_WARNINGS 
#ifndef _TreasureSeeker_H 
#define _TreasureSeeker_H 
#include "GamePiece.h" 
#include "Player.h" 
#include "Treasure.h" 
#include"Enemy.h" 
#include"Trap.h" 

using namespace std; 

//class Treasusekeer 

class TreasureSeeker 
{ 
public: 
    TreasureSeeker(); 
    ~TreasureSeeker(); 
    void play(); 
    void save(ofstream & out)const; 
    TreasureSeeker(ifstream& in); 
    void setname(); 
private: 
    Player *p1;//obj to player 
    Treasure* t1;//obj to Treasure 
    Trap *trap1;//obj to Trap 
    Enemy *en1;//obj to Enemy 
    GamePiece borad[9][9]; 
    GamePiece *emp1;//obj empty 
    GamePiece temp;//obj temp to save for a enemy move 
    void check(int flag); 

    void print(); 
    void del(); 
    void check(int i, int j, int move); 
    void step(); 
    void checkenemy(int p); 
}; 

#endif 

Это Func скопировать:

void TreasureSeeker::save(ofstream & out)const 
{ 
    out.write((const char*)this, sizeof(*this)); 
} 

TreasureSeeker::TreasureSeeker(ifstream& in) 
{ 
    in.read((char*)this, sizeof(*this)); 
} 

игрок:

#include "GamePiece.h" 
#ifndef _Player_H 
#define _Player_H 

//class player 

class Player : public GamePiece 
{ 

public: 

    Player(); 
    ~Player(); 
    void print(); 
    int Neutralization(); 
    int Step(); 
    int getX(){ return this->placeX; } 
    int getY(){ return this->placeY; } 
    void setx(int x){this->placeX = x;} 
    void sety(int y){this->placeY = y;} 
    void fight(); 
    void findknife(); 
    void setn(string d){ this->nameplayer = d; } 

private: 
    string nameplayer; 
    int knife; 
    int placeX; 
    int placeY; 
    int killenemy; 
    int killtrap; 

}; 
#endif 

ловушка:

#include"GamePiece.h" 
#ifndef _Trap_H 
#define _Trap_H 

class Trap :public GamePiece 
{ 
public: 
    Trap(); 
    ~Trap(); 
    void puttrap(int x,int y); 
    int getnumoftrap(); 
private: 
    int numoftrap; 
}; 

#endif 

и Treasure:

#include"GamePiece.h" 
#ifndef _Treasure_H 
#define _Treasure_H 
class Treasure :public GamePiece 
{ 
public: 
    Treasure(int x, int y); 
    ~Treasure(); 
    int getX(); 
    int getY(); 
    int Gettrusefake(); 

private: 
    int TreasureX; 
    int TreasureY; 
    int Treasurefake; 
}; 

#endif 

и Borad из этого класса:

#define _CRT_SECURE_NO_WARNINGS 
#ifndef _GamePiece_H 
#define _GamePiece_H 
#include <iostream> 
#include <string> 
#include <cstring> 
#include <fstream> 
#include <ctype.h> 
#include <time.h> 
#include <typeinfo> 
#include <stdlib.h> 
using namespace std; 

//class gamepiece +func get set print 

class GamePiece 
{ 
public: 
    GamePiece(){ nametool = "Empty Cell"; charname = 'O'; } 
    ~GamePiece(){}; 
    void printname(){ cout << "name tool is :" << nametool << endl; } 
    void printchar(){ cout << charname; } 
    virtual void step(){}; 
    char getname(){ return charname; } 
    string getoolname(){ return nametool; } 
    void setcharname(char p){ charname = p; } 



private: 
    string nametool; 
    char charname; 
}; 

#endif 

и это FUNC играть:

cout << "Hello to Find the Treasure game" << endl; 
    int save = 1; 

    do 
    { 
     cout << endl; 
     p1->print(); 
     cout << endl; 
     print(); 
     step(); 
     cout << endl; 
     print(); 
     cout << "to save end exit prees 0 to continue prees 1 :" << endl << " your choise : "; 
     cin >> save; 
    } while (save); 

} 
+2

зашифрованы ли этот вопрос? Кто-нибудь знает, что такое закрытый ключ? –

+1

Что заставляет вас думать, что вы можете просто сериализовать свой класс в файл и вернуть его позже? Указатели нельзя воссоздать. –

+0

так может у меня руководство, что делать, чем я могу Сохранение и загрузка игры, пожалуйста? –

ответ

3
void TreasureSeeker::save(ofstream & out)const 
{ 
    out.write((const char*)this, sizeof(*this)); 
} 

Вы можете сделать это, только если все члены данных класса являются POD types и не владеют ресурс, даже при том, что , наступает вопрос structure padding.

Бесплатный совет, не делайте этого прямо, его обычно не переносят даже для не-ресурсных владельцев типов POD.

ПРИМЕЧАНИЕ. Указатель либо владеет, либо ссылается на ресурс (память).

Различные компиляторы могут pad your structure и выложить их в памяти по-разному.

TreasureSeeker::TreasureSeeker(ifstream& in) 
{ 
    in.read((char*)this, sizeof(*this)); 
} 

В дополнение к тому, что я сказал ранее, это также довольно плохая идея. Вы находитесь в контексте this, и внешне изменения всей this, в то время как его живым ....


Чтобы решить проблему, читайте О Serialization in C++

Смежные вопросы