2010-09-23 38 views
0

嗨,我正在寫一些代碼,我發現了一個奇怪的錯誤。函數convert_vector2d(& i_scale)將字符串轉換爲vector2d(從sf :: vector2f繼承)。如果您檢查接下來的幾行代碼,我將執行兩次相同的操作。存儲返回值,然後使用vs直接使用C++

代碼:選擇所有

float x = convert_Vector2D(&i_scale).x; 
float y = convert_Vector2D(&i_scale).y; 
object.SetScale((convert_Vector2D(&i_scale))); 
ss = object.GetScale(); 
object.SetScale(x , y); 
ss = object.GetScale(); 

我第一次調用setScale與convert_vector2d和SS = 1,1返回向量。然後我再次用x,y(存儲的結果)調用object.setScale,當我調用object.getScale時,我得到ss = 1,2(這是預期的/正確的)。

我通過了convert函數,它通過兩個函數調用返回1,2。

代碼:選擇爲什麼我得到不同的行爲,所有

const Vector2D Map::convert_Vector2D(std::string * string_to_convert) 
{ 
    size_t foundit = 0; 
    Vector2D temp; 
    std::string one, two; 
    if((foundit = string_to_convert->find(',')) != std::string::npos && 
     string_to_convert->find_first_of(',') == string_to_convert->find_last_of(',')) // only one comma per line. 
    { 
     one = string_to_convert->substr(0, foundit); 
     two = string_to_convert->substr(foundit+1, string_to_convert->size()); // +1 to skip over the comma. 

     temp.x = (float)strtod(one.c_str(), NULL); 
     temp.y = (float)strtod(two.c_str(), NULL); 

     check_conversion_errors_vector2d(temp, string_to_convert); 
    } 
    else 
    { 
     Debugger::print("MapLoader: Error: more then one comma on line %d of file %s. Stopping reading of file.\n", 
      i_Current_Line, mMapName.c_str()); 
     i_QuitParsing = true; // TODO: maybe add return after this line? 
    } 

    return temp; 
} 

任何想法?

void Drawable::SetScale(float ScaleX, float ScaleY) 
{ 
    SetScaleX(ScaleX); 
    SetScaleY(ScaleY); 
} 

void Drawable::SetScale(const Vector2f& Scale) 
{ 
    SetScaleX(Scale.x); 
    SetScaleY(Scale.y); 
} 

void Drawable::SetScaleX(float FactorX) 
{ 
    if (FactorX > 0) 
    { 
      myScale.x  = FactorX; 
      myNeedUpdate = true; 
      myInvNeedUpdate = true; 
    } 
} 


void Drawable::SetScaleY(float FactorY) 
{ 
    if (FactorY > 0) 
    { 
      myScale.y = FactorY; 
      myNeedUpdate = true; 
      myInvNeedUpdate = true; 
    } 
} 

SFML拷貝構造函數和成員變量:

// = equals operator assignment 
Vector2D& operator=(const Vector2D &rhs) 
{ 
    if(this == &rhs) 
    { 
     return *this; 
    } 
    else 
    { 
     this->x = rhs.x; 
     this->y = rhs.y; 
     return *this; 
    } 
} 
// = equals operator assignment 
Vector2D& operator=(const sf::Vector2f &rhs) 
{ 
    this->x = rhs.x; 
    this->y = rhs.y; 
    return *this; 
} 

float x, y; 
+0

這兩個'SetScale()'函數是什麼樣的? – 2010-09-23 22:36:10

+0

已添加到原始帖子。 – 2010-09-23 22:53:35

+1

你能向我們展示'Vector2f'和'Vector2D'的代碼(特別是成員變量和任何拷貝構造函數)嗎?我懷疑你可能有兩個聲明'x'和'y'的成員。 – Doug 2010-09-24 03:09:11

回答

0

不要在棧上分配的Vector2D,做它用新的堆。您對函數外部的temp的引用是未定義的,可能是垃圾。

+0

我返回值,通過返回值,我認爲我沒有引用變量temp存儲在堆棧了,因爲它被返回? – 2010-09-23 22:59:04

+2

@Ben:你正確使用它。我懷疑@user誤讀你的代碼。 :) – 2010-09-23 23:16:24

+0

非常外交喬納森,我一直在Java編碼太久我的腦電線越過... – user318904 2010-09-24 21:57:15

相關問題