Suppose I have a code as following.
class Color
{
static Color a;
public:
static Color newColor(int r,int g,int b){
Color color;开发者_运维知识库
color.setR(r);
color.setG(g);
color.setB(b);
return color;
}
}
Is it alright to initialize the static variable 'a' using 'Color a = Color::newColor(255,0,0);' I think I read somewhere that creating the instance using this method will create two instances of the class. What is the right way of doing this?
Yes Color gets instantiated twice
- the local variable color in newCOlor and
- the static Color a (since you are returning an object, a member-wise copy will happen at the static variable definition/initialization).
Be sure to put Color::a = Color::newColor(255,0,0); in a cpp/cc file, meaning not in a header file.
Try this for size:
struct Color
{
int R, G, B;
};
Color a = {255, 0, 0};
精彩评论