我的课程看起来像
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;
}
现在我想在另一个类中使用上面定义的结构,如下面的
structTest::structTest(void)
{
}
structTest::~structTest(void)
{
}
void structTest::test(void)
{
// goes here
Games *structptr = new Games;// This not working ....
}
我该怎么做..当我尝试它时会抛出'没有合适的默认构造函数'错误...
答案 0 :(得分:2)
看起来您的struct Games
在一个文件中声明,structTest
在另一个文件中声明。是吗?
您的structTest
类需要查看Games
结构的定义才能生效。
将Games
结构放在自己的文件中(可以称之为Games.h
)。 #include
这个文件包含您的main
函数以及定义structTest
类的文件。
请注意,Unreal
和Blizzard[3]
仍然需要包含main
函数的文件,而不是头文件中的文件,该文件应仅包含struct
定义(如果您打算在其他模块中使用它,也可以选择typedef
。)
答案 1 :(得分:1)
我认为你应该改进你的格式,因为即使在这个时候它已经变得难以阅读。我几乎没有想到在你的项目的后续阶段会发生什么。
现在 - 直接回答问题。
我想你想拥有以下内容:
struct Games {
// whatever
bool value;
};
struct GamesHolder {
Games games;
};
现在,如果Games
不仅仅是一个原始数据持有者,而是代表某种抽象或持有太多数据放在堆栈上,你可能想要使用以下模式:
struct GamesHolder {
Games* games_pointer;
};
现在可以通过以下方式实现初始化:
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.
只要有时手动内存管理在* ss中变得很麻烦,您也可能想要开始使用共享指针:
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.