2016-09-30 72 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:“垃圾”? –