Hi, i have been learning C++ and SFML and have been wondering a few things.
1) In the event tutorials the code sf::Event event;
gets placed inside of the while (window.isOpen()) {
loop but wouldn't this mean is is created many times? I would have expected it to get added after the RenderWindow was made at the top.
2) Also in the examples it uses sf:: but can this be removed with a "using namespace" so something like sf::Text text("Hi", font);
would then be Text text("Hi", font);
When i have used this with some simple examples for std:: i think doing that made the code seem simpler. Does it remain in the examples to help avoid name conflicts or something?
3) I notice that with C++ i can't just combine a string and int ("Hello" + 123 etc) which is simple with many other programming languages, i figured out the solution by using ostringstream however it then made what is normally a 1 line of code into about 4 instead.
For example i was originally expecting this type of code to work -
// Mouse wheel moved
if (event.type == sf::Event::MouseWheelMoved) {
text.setString("Mouse wheel moved" + event.mouseWheel.delta);
}
but it seems to instead cut off letters like it's a substring.
So i fix it with -
if (event.type == sf::Event::MouseWheelMoved) {
ostringstream d; d << event.mouseWheel.delta;
text.setString("Mouse wheel moved " + d.str());
}
So for more complex things you then need to use more code. I looked in the string class reference but didn't notice anything, does SMFL have any simple way/function to do this?
Thanks
1. There's no "creation". sf::Event is a trivial union with no constructor, declared on the stack. Creating such an instance is a no-op.
Generally speaking, it's better to create objects only where you need them, because:
- sometimes they have constructors with parameters, and these parameters may not be known in advance
- it improves the readability of the code
- it avoids to pollute the function, by keeping variables in small scopes
2. It's a matter of taste. But think about it: namespaces do not exist for people to cancel them everytime with "using namespace xxx" ;) They improve readability, by explicitly showing which library a function/class belongs to.
3. C++11 has the to_string function. Otherwise it's easy to create, just put your stringstream code into a template function.
template <typename T>
std::string to_string(T value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
...
text.setString("Mouse wheel moved" + to_string(event.mouseWheel.delta));