开发者

Creating Class Objects from Static Functions

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

  1. the local variable color in newCOlor and
  2. 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};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜