开发者

c++ class member of same type

I have the following situation:

clas开发者_开发问答s Foo
{
public:
  static const Foo memberOfFoo;

  ........
}

So the thing is I can't initialize it in the same line where I declared it, and, I can't initialize it via Initializations List in the constructor, does anyone know what to do?


Put this outside of the class definition then:

const Foo Foo::memberOfFoo = whateverValue;

That is the definition of Foo::memberOfFoo, which can supply an initializer and has to go into the .cpp file (like any other definition of objects, it can only appear once in the whole program, otherwise you will get linker errors).

Sometimes you will find code that doesn't have definitions for its static data members:

struct A {
  // sometimes, code won't have an "const int A::x;" anywhere!
  static const int x = 42;
};

Omitting the definition like that is valid only if A::x is never address-taken and never passed to reference parameters. A more formal way to say when it is valid to omit the definition is: "When all uses of A::x immediately read the stored value of A::x". That's the case for many static integer constants.


Class statics other than constant integral types need to/can be initialized at the point of definition. You need to declare your (not so)memberOfFoo somewhere, by adding

const Foo Foo::memberOfFoo = /*construct here*/;


This is how you can implement initialization...

class Foo
{
public:
    static const Foo memberOfFoo;

    Foo(int, double)
    {
        ...
    };
};

const Foo Foo::memberOfFoo(42, 3.141592654);

...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜