Hello i am trying to make my code more editable and more Object Oriented.
I want to have a const struct in my namespace called TileType.
It have two const Properties.
But i can't initialize it in a namespace of course. I dont know how to solve it even tho its very basic.
So any ideas?
EDIT: I know i can make a class and make functions that just returns constants but it feels like a ugly solution for an editable code. Is it possible another way?
constant objects can be initialised in header files
(although to be fair - the extern method as shown by WebJose might be better
as you might change your mind about the object being constant, and then end up getting problems with miltiple definitions when you remove the const keyword)
There's constant and there is constant.
It might mean a trawl through the c++ standard doument of what constitutes a
compile time constant expreesion that is suitable.
Trying to do it the way you are doing has never been acceptable.
However C++11 intoduces the constexpr keyword which we use
to gaurantee to the compiler that the value we are using is a genuine constant.
This will work with what you are trying to do.
Example:
class xyza
{
public:
constint yy;
};
int main()
{
constexpr xyza qqq{23}; //use constexpr keyword instead of const keyword.
int abc(3);
switch (abc)
{
case qqq.yy: //now we can use a member name
break;
default:
break;
}
}
You will however, need a C++11 compliant compiler.
// header file - For example myheader.h
#ifndef my_header_h
#define my_header_h
namespace namespaceX
{
class XYZA
{
public:
constint yy;
};
//constant expressions can be defined in header files
//we can define our constant structures here
//note that we use constexpr rather than const keyword.
constexpr XYZA qqq{23};
}
#endif
//some cpp file
#include "myheader.h"
namespace namespaceX
{
}
//main.cpp
#include "myheader.h"
int main()
{
int abc(21); //test value
switch (abc)
{
case namespaceX::qqq.yy: //now we can use a member name
cout << namespaceX::qqq.yy << endl;
break;
default:
cout << "No match" << endl;
break;
}
}
EDIT:
For the record, the code as shown compiles and runs with mingw/gcc 4.7 with -std=c++11 compiler switch.
Hello, I have take a look at this solution with the constexpr keyword. I felt that i made my code unstructured and im now working on some kind of class.