I have class which looks like
struct Games
{ char Name[80];
char Rating;
bool Played;
long NumberOfKills;
} Unreal, Blizzard[3];
typedef Games* Gamesptr;
int _tmain(int argc, _TCHAR* argv[])
{
int x;
Gamesptr ptr = new Games;
return 0;
}
Now i want to use the struct defined above in another class like below
structTest::structTest(void)
{
}
structTest::~structTest(void)
{
}
void structTest::test(void)
{
// goes here
Games *structptr = new Games;// This not working ....
}
how do i do this ..when I tried it throws me ' no appropriate default constructor available' error...
It looks like your struct Games
is declared in one file, and structTest
in another file. Is that right?
Your structTest
class needs to see the definition of the Games
struct in order to work.
Put the Games
struct in its own file (maybe call it Games.h
). #include
this in the file that includes your main
function and in the file that defines the structTest
class.
Note that Unreal
and Blizzard[3]
still need to be in the file that includes your main
function, not in the header file, which should contain only the struct
definition (and optionally the typedef
if you plan to use that in other modules).
I think you should improve your formatting, because even at this moment it has already become hard to read. I can hardly ever think of what might happen at the following stages of your project.
Now - directly to the question.
I think you want to have the following:
struct Games {
// whatever
bool value;
};
struct GamesHolder {
Games games;
};
Now, if the Games
isn't just a raw data holder, but stands for some kind of the abstraction or holds a too much data to be placed on the stack, you might want to use the following pattern:
struct GamesHolder {
Games* games_pointer;
};
The initialization now may be implemented the following way:
GamesHolder games_holder;
games_holder.games_pointer = new Games(...whatever);
// If the memory is not cleared when the 'games_holder'
// leaves the scope - bang - a memory leak.
As long as sometimes manual memory management becomes a pain in the *ss, you also might want to start using shared pointers:
struct GamesHolder {
std::shared_ptr<Games> games_pointer;
}
GamesHolder games_holder;
games_holder.games_pointer.reset(new Games(...));
// No leak if the 'holder' leaves the scope - memory
// is being automatically disposed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.