No Im not sure, I've just started to learn C++ and its not in the book I have (Game Institute, Game Programming 1).
But could you give me a link to an explanation / example?
Printable View
Hm, now I just changed some code and it works.
Earlier:
Changed To:Code:#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include "items.h"
using namespace std;
int Init()
{
Weapon ShortSword;
ShortSword.Create("Short Sword", "Common", 1, 10, 1, 4);
}
int main()
{
srand(time(0));
Init();
cout << ShortSword.mName;
system("pause");
return 0;
}
So basically all I did was to create the structure in main, instead of in a function with the creation that is called in main.Code:#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include "items.h"
using namespace std;
int main()
{
srand(time(0));
Weapon ShortSword;
ShortSword.Create("Short Sword", "Common", 1, 10, 1, 4);
cout << ShortSword.mName;
system("pause");
return 0;
}
Can someone explain why it works to create it in main, but not in a function which is called in main?
Thanks.
Apparently not, since it took 12 posts for someone to address what he was actually wanting to do.
Unless you happen to be fluent in machine code, you're a lowly human in this context.Quote:
As for being a lowly human, that is a career choice.
(so I assume you speak for yourself)
http://en.wikipedia.org/wiki/Scope_(programming)Quote:
Can someone explain why it works to create it in main, but not in a function which is called in main?
http://en.wikipedia.org/wiki/Variabl...ope_and_extent
If the book you're learning from has gotten you into functions and structures without explaining something as basic as scope, I'd really suggest looking for another book.
I do understand scopes, but what im asking is: do you have to create structures in main like this:
And is it impossible to create them in void functions which is called in main when to create them?Code:int main()
{
Weapon sword;
Weapon dagger;
Weapon axe;
Weapon bow;
}
Its hard to explain it when everyone is thinking so complex.Code:void Call();
int main()
{
Call();
}
void Call()
{
Weapon sword;
Weapon dagger;
Weapon axe;
Weapon bow;
}
There are various methods to have a function create objects that are useable after that function ends. Namely, have the function take some STL container by reference and insert the objects into that container.Code:void Call( )
{
Weapon sword;
Weapon dagger;
Weapon axe;
Weapon bow;
} // <-- sword, dagger, axe and bow go out of scope at this point, and no longer exist
Simple example using a map:
Code:typedef std::map<std::string, Weapon> WeaponMap;
void Create(WeaponMap& wm)
{
wm["sword"] = Weapon(/*params*/);
wm["dagger"] = Weapon(/*params*/);
// etc
}
int main( )
{
WeaponMap weps;
Create(weps);
cout << weps["sword"].mName;
return 0;
}
I think I understand how it works now, thanks mate.