-
Yeah, I forgot I was working with std::string, I just didn't think about it because that wasn't my main problem, but I appreciate you guys reminding me. Direct comparison is much easier and less bloated than the old C-style string way; bad habits from Win32 API programming mixed with C, bleh.
Anyways, I wrote a virtual draw function in my base Sprite class, and now it works perfectly! :D
pheres:
That looks incredibly more efficient and EXACTLY what I was looking for, I was just about to ask if there was any other more efficient way than to compare each string like that. I hate repetitive programming as there are almost always better, faster, and slimmer ways to code it. Thanks a lot everybody, I'm off to check out std::map and then continue my project! woo!
-
one way you could create the dictionary without using function pointers (I find code using function pointers to be very C-like, so personally I prefer to avoid them if there's an easy workaround) -
Code:
class ISpriteCreator //Sprite Creator interface
{
public:
virtual Sprite* Create(int int) = 0;
};
template<class ConcreteSprite>
class SpriteCreator : public ISpriteCreator
{
public:
Sprite* Create(int x, int y)
{
return new ConcreteSprite(x, y);
}
};
// .. dictionary mapping strings to sprite creators
std::map<std::string, ISpriteCreator*> dictionary;
dictionary.insert( std::make_pair( "LeftCloud", new SpriteCreator<LeftCloud> () ) );
-
Alright yeah, that looks good. I'll give that a try.
But one other thing, when I did this:
Code:
SpriteFactory* factory = new ConcreteFactory();
Sprite* test = factory->getSprite(0);
...
test->draw();
It worked perfectly. However, when I try ANY other value than 0 here (and yes, the numbers I tried are valid numbers for the sprite index) I get a segfault.
Here's an example of what would give me a segfault.
Code:
SpriteFactory* factory = new ConcreteFactory();
Sprite* test = factory->getSprite(1);
...
test->draw();
Any ideas on why this would happen?
Thanks again!
-
Cancel that, I know why I got a segfault.
I'm going to go put that std::map in to get rid of those repetitive if statements, thanks a bunch to everyone, you helped me a great deal :)