2016-09-30 74 views
-4

你好,即時通訊char *有問題是相同的一個奇怪的方式。 Color :: Text()返回一個靜態char數組,但它也用於初始化數組的const char *指針。Const char *怪異行爲

wtf我做的如果我想rofl ::默認實際工作,而不是最新的「const char」它顏色::文本生成?

#include <windows.h> 
class Color 
{ 
public: 
    int R; 
    int G; 
    int B; 
    int A; 
    Color(int r, int b, int g, int a = 255) 
    { 
    R = r; 
    G = g; 
    B = b; 
    A = a; 
    } 
    const char* Text() 
    { 
    static char Texts[124]; 
    snprintf(Texts, 124, "%i %i %i %i", R, G, B, A); 
    return Texts; 
    } 
} 
class rofl 
{ 
public: 
    const char* Default; 
    const char* Value; 
    rofl(const char* d) 
    { 
     Default = d; 
     Value = d; 
    } 
} 

rofl dood("0"); 
rofl doaaod(Color(0,0,0).Text()); 
rofl xxxx(Color(0,55,0).Text()); 

int main() 
{ 
    printf("%s %s\n", dood.Default, dood.Value); 
    printf("%s %s\n", doaaod.Default, doaaod.Value); 
    printf("%s %s\n", xxxx.Default, xxxx.Value); 
    return 0; 
} 

輸出爲:

0 0 
0 55 0 0 0 0 
0 55 0 0 55 0 
+0

在'rofl'的構造函數中爲'Default'和'Value'指定一個緩衝區(例如使用operator'new')。然後將數據複製到這些緩衝區。更好的是,使用'std :: string'對象而不是'char *',並且動態分配將被幹淨地管理。 – Peter

回答

1

你在你的代碼(除文字字符串)只有一個字符緩衝區。 A const char*是指向字符緩衝區的指針,而不是作爲原始副本的新緩衝區。

因此,每次調用Color :: Text時,都會寫入相同的字符緩衝區,並且所有指向它的指針都會讀取它們是很自然的。

您必須瞭解C和C++中指針的概念。

在這種情況下,在C++中,對於您需要的行爲,您應該用std::string替換const char*的所有用法。

我推薦你使用「加速C++」一書來輕鬆學習C++,而不需要進入語言中過時的細節。

+0

我不能使用垃圾像std :: string – Lolmelon

+1

@Lolmelon:你的問題被標記爲[標籤:C++]。如果您不能使用C++,請不要像這樣標記它。 – IInspectable

+0

@Lolmelon:「垃圾」? –