我已经写了这段代码。它没有给出编译时错误,但给出运行时错误。你能告诉我这段代码有什么问题吗?
它给出了这个运行时错误->带信息:vpid 1:终止于信号11
#include <iostream>
class Color
{
public:
static Color White, Black, Red, Green, Blue;
unsigned char red, green, blue;
static void static_Color();
Color(unsigned char _red
, unsigned char _green
, unsigned char _blue)
: red(_red), green(_green), blue(_blue)
{
static_Color();
}
Color()
{
static_Color();
}
};
Color Color::White, Color::Black
, Color::Red, Color::Green, Color::Blue;
void Color::static_Color()
{
static bool called_before = false;
if(called_before)
return;
Color::White = Color(255, 255, 255);
Color::Black = Color(0, 0, 0);
Color::Red = Color(255, 0, 0);
Color::Green = Color(0, 255, 0);
Color::Blue = Color(0, 0, 255);
called_before = true;
}
int main()
{
std::cout << (int) Color::Red.red;
}
您不需要
static_Color()
功能。只需使用定义了 static
颜色的正确值初始化它们即可:
class Color {
public:
static Color White, Black, Red, Green, Blue;
unsigned char red, green, blue;
static void static_Color();
Color(unsigned char _red, unsigned char _green, unsigned char _blue)
: red(_red), green(_green), blue(_blue) {}
Color() = default;
};
// Here:
Color Color::White = Color(255, 255, 255);
Color Color::Black = Color(0, 0, 0);
Color Color::Red = Color(255, 0, 0);
Color Color::Green = Color(0, 255, 0);
Color Color::Blue = Color(0, 0, 255);