Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Const char*奇怪的行为_C++_Static_Undefined Behavior_Behavior - Fatal编程技术网

C++ Const char*奇怪的行为

C++ Const char*奇怪的行为,c++,static,undefined-behavior,behavior,C++,Static,Undefined Behavior,Behavior,您好,我对const char*以一种奇怪的方式保持不变有问题。 Text返回一个静态字符数组,但也用于初始化数组的const char*指针 如果我希望rofl::Default实际工作,而不是最新生成的const char it Color::Text,我该怎么办 #include <windows.h> class Color { public: int R; int G; int B; int A; Color(int r, int b

您好,我对const char*以一种奇怪的方式保持不变有问题。 Text返回一个静态字符数组,但也用于初始化数组的const char*指针

如果我希望rofl::Default实际工作,而不是最新生成的const char it 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;
}

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

因此,每次调用Color::Text时,您在同一个字符缓冲区上写入的内容和指向它的所有指针读取的内容都是相同的,这是很自然的

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

在此情况下,在C++和您需要的行为中,您应该替换STD::String。< /P>的const char的所有用法。


我推荐你的书,加速C++学习C++,而不涉及到语言中有点陈旧的细节。在rfl的构造函数中,

创建一个缓冲区,例如使用new new作为默认值和值点。然后将数据复制到这些缓冲区。更好的是,使用std::string对象而不是char*,动态分配将为您进行干净的管理string@Lolmelon:您的问题已标记。如果你不能使用C++,不要把它标记为“@ Loal甜瓜:垃圾”。你决定是否要学习现代C++或1970年代风格的编程。在这种情况下,阅读C编程语言,您最终将完全理解代码的问题。
0 0
0 55 0 0 0 0
0 55 0 0 55 0