Const char *奇怪的行为

时间:2016-09-30 09:40:22

标签: c++ static undefined-behavior behavior

你好我的const char *有一个奇怪的方式相同的问题。 Color :: Text()返回一个静态char数组,但它也用于初始化数组的const char *指针。

如果我想要rofl :: Default实际工作并且不是最新的“const char”,我会这样做吗?Color :: Text产生了吗?

#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

1 个答案:

答案 0 :(得分:1)

代码中只有一个字符缓冲区(除文字字符串外)。 const char*是指向字符缓冲区的指针,而不是作为原始文件副本的新缓冲区。

因此,很自然地,每次调用Color :: Text时,您都在相同的字符缓冲区上写入,并且所有指向它的指针都会读取相同的内容。

你必须理解C和C ++中指针的概念。

在这种情况下,在C ++中,对于您需要的行为,您应该将const char*的所有用法替换为std::string

我推荐你的书#34; Accelerated C ++&#34;学习C ++很容易,而不需要进入语言中有点过时的细节。

相关问题