你好,即时通讯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
在'rofl'的构造函数中为'Default'和'Value'指定一个缓冲区(例如使用operator'new')。然后将数据复制到这些缓冲区。更好的是,使用'std :: string'对象而不是'char *',并且动态分配将被干净地管理。 – Peter