Yevhen
Yevhen

Reputation: 1975

Constant member

I have structure defined in some header (D3DXVECTOR3)

How can I declare:

  1. static member in the class of that type and initialize it?
  2. maybe constant member of that type and init it?

when i use some constructor i get error only integral can be initialized.

Upvotes: 1

Views: 200

Answers (4)

Yevhen
Yevhen

Reputation: 1975

in header file I declared

class Bar_class
{
  static const D3DXVECTOR3 foo;
}

in cpp file I wrote

const D3DXVECTOR3 Bar_class::foo =D3DXVECTOR3 (1,1,1);

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546083

To have a static member of non-int type, use the following construct:

class foo {
    // Declarations:
    static Type1 field1; // or
    static Type2 const field1;
};

// Definitions and initializations:
Type1 foo::field1 = value1;
Type2 const foo::field2 = value2;

Upvotes: 1

Prasoon Saurav
Prasoon Saurav

Reputation: 92924

Use initializer list to initialize const members.

For example

struct demo
{

    const int x;

    demo():x(10)
    {
        //some code
    }

};

As far as initializing static members(inside the class) is concerned (you can initialize them inside the class only if they are const-static integers)

For example

struct abc{

     static const int k=10; //fine
     static int p=10; //Invalid
     static const double r =2.3 //Invalid
      // ......

   };

  const int abc::k ; //Definition

Upvotes: 1

ProgramMax
ProgramMax

Reputation: 97

You can't just modify the already-existing struct. That would be a redefinition. Not fun stuff.

You can wrap it like TGadfly suggested.

Upvotes: 1

Related Questions