Sign in to follow this  
Finalspace

How to initialize a static field in c++?

Recommended Posts

I have the following code which have 4 static members in the struct. Why can i not initialize it?

I just want a bunch of predefined vectors i can use -.-

 

Error i get: LNK2005    "public: static union Vec2f const Vec2f::Up" (?Up@Vec2f@@@2T123@A) already defined

		union Vec2f {
			struct {
				f32 x;
				f32 y;
			};
			struct {
				f32 w;
				f32 h;
			};
			f32 elements[2];

			inline Vec2f() {
				x = y = 0;
			}
			inline Vec2f(f32 value) {
				x = y = value;
			}
			inline Vec2f(f32 newX, f32 newY) {
				x = newX;
				y = newY;
			}
			inline Vec2f(const Vec2f &from) {
				x = from.x;
				y = from.y;
			}
			
			static const Vec2f Up;
			static const Vec2f Down;
			static const Vec2f Left;
			static const Vec2f Right;
		};

		const Vec2f Vec2f::Up = Vec2f(0, 1);
		const Vec2f Vec2f::Down = Vec2f(0, -1);
		const Vec2f Vec2f::Left = Vec2f(-1, 0);
		const Vec2f Vec2f::Right = Vec2f(1, 0);

 

Edited by Finalspace

Share this post


Link to post
Share on other sites
6 minutes ago, _Silence_ said:

Put the initialization in the source file, not the header file.

There is no source file, its a math header file. But well another source file wont hurt... so putting the initialization stuff into the source file works. Thanks.

7 minutes ago, Sponji said:

How about


struct Vec2f {
	union {
		struct {
			f32 x;
			f32 y;
		};
		struct {
			f32 w;
			f32 h;
		};
		f32 elements[2];
	};
  // ...

 

How about what? I dont see anything at all...

Edited by Finalspace

Share this post


Link to post
Share on other sites
11 minutes ago, Finalspace said:

How about what? I dont see anything at all...

1

Yeah my bad, not sure what I was thinking, dunno why it looked so weird for me having a union with constructors. Didn't notice it was a linker error.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this