Creating a fixed-size vector in a C++ header file.
Hi everyone,
I get compiler syntax errors when I run the following:
===========================================================
// SoundSystem.h
#include <vector>
#include <stdio.h>
#define MAX_CHANNELS 10
using namespace std;
class SoundSystem
{
private:
int val1;
int val2;
int val2;
vector<Channel*> channels(MAX_CHANNELS);
public:
UpdateChannels();
...
};
===========================================================
Visual Studio says the error occurs when I declare that vector. When I take out (MAX_CHANNELS) so that it's not fixed-sized, the code runs. Interestingly, when I declare that vector inside one of my functions (and comment that declaration out in my header), it compiles just fine.
The error I get is:
error C2059: syntax error: 'constant'
error C2059: syntax error: 'constant'
fatal error C1903: unable to recover from previous error(s); stopping compilation.
I don't understand why I can't declare the fixed-sized array there in the header, but can in functions. The following code also compiles:
==========================================================
class SoundSystem
{
private:
int val1;
int val2;
int val2;
public:
UpdateChannels()
{
vector<Channel*> channels(MAX_CHANNELS);
}
...
};
==========================================================
Is this a Visual Studio bug? For the record, I'm using Visual Studio 2003 .net
Thanks for the help,
Tek
You can construct member variables in the member initializer lists for your constructors, like this:
Also it's better to scope explicitly than to have 'using' declarations in your header files.
class SoundSystem{public: SoundSystem();private: std::vector<Channel*> channels;};SoundSystem::SoundSystem() : channels(MAX_CHANNELS) {}
That should do what you're wanting.Also it's better to scope explicitly than to have 'using' declarations in your header files.
That works, thanks a lot!
Because a vector still has a lot of nice functions a simple array doesn't have, and I want to be consistent :)
Quote:Original post by Nypyren
Since you're using a fixed size vector of pointer-types, why not just use a simple array?
Because a vector still has a lot of nice functions a simple array doesn't have, and I want to be consistent :)
Quote:Original post by tekmoto
That works, thanks a lot!Quote:Original post by Nypyren
Since you're using a fixed size vector of pointer-types, why not just use a simple array?
Because a vector still has a lot of nice functions a simple array doesn't have, and I want to be consistent :)
Then check Boost.Array out. [smile]
It’ll allow you to use stuff like:
class SoundSystem { public: SoundSysmtem() { std::fill(channels.begin(), channels.end(), new Channel); } private: boost::array<Channel*, MAX_CHANNELS> channels; };
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement