2012-03-20 33 views
-1

讓我解釋一下這種情況:無法獲得的另一種載體內從矢量數據

我有一個類cAnimation有幾個方法

#include "SDL/SDL.h" 
#include <vector> 
#include <fstream> 

using namespace std; 

class cAnimation{ 

    private: 
     vector<SDL_Rect> frames; 

    public: 
     cAnimation(); 
     void setQntFrames(int n){ 
      this->frames.resize(n); 
      ofstream log("qntframes.txt"); 
      log << "capacity = " << this->frames.capacity(); 
     } 

     void setFrame(int index,int x, int y, int w, int h){ 
      this->frames[index].x = x; 
      this->frames[index].y = y; 
      this->frames[index].w = w; 
      this->frames[index].h = h; 

      ofstream log("setrect.txt"); 
      log << "i = " << i 
       << "x = " << this->frames.at(i).x 
       << "y = " << this->frames.at(i).y 
       << "w = " << this->frames.at(i).w 
       << "h = " << this->frames.at(i).h; 
     } 

     SDL_Rect cAnimation::getFrame(int index){ 
      return this->frames[index]; 
     } 
}; 

我在我的main.cpp這樣做(在包括都行)

vector<cAnimation> animation; 

animation.resize(1); 
animation[0].setQntFrames(10);   // it's printing the right value on qntframes.txt 
animation[0].setFrame(0,10,10,200,200) // it's printing the right values on setrect.txt 

SDL_Rect temp = animation[0].getFrame(0);// here is the problem 

ofstream log("square.txt"); 
log << "x = " << temp.x 
    << "y = " << temp.y; 
當我看向square.txt日誌

,看起來像正方形一些奇怪的字符,當我嘗試去SDL_Rect臨時的數據使用,應用剛剛結束,我在做什麼這裏弄錯了值?

+3

請閱讀http://sscce.org,瞭解如何以及爲什麼您應該將代碼減少到一個簡單的測試用例。 – 2012-03-20 17:22:35

回答

-1

您可能正在輸出字符。將這些輸出到ostream時,您將獲得ASCII字符,而不是ASCII字符的數字值。試試這個:

log << "x = " << (int) temp.x 
    << "y = " << (int) temp.y; 

'char'經常用作1字節整數的簡寫。它們適用於此目的,除了將它們輸出到流時,它會嘗試將它們輸出爲ASCII字符,而不是一個字節的整數。將角色轉換爲真正的整數通常可以解決問題。

+0

仍然在文件上保存相同的奇怪字符,這可能是一些錯誤的內存訪問? – 2012-03-20 17:26:32

+2

SDL_Rect組件不是char類型。它們是Sint16,它在大多數系統上只是一個「short」的typedef。 – 2012-03-20 17:27:43

+0

我在方法上使用相同的「模式」保存數據,只是在那裏我從矢量幀中獲取數據的溫度並不節約,並且當我嘗試使用temp來終止同一瞬間時終止做一點事。 – 2012-03-20 17:28:59