我的两个类必须包含对方。我做了前面的声明,编译没问题。这些类的一个功能是调用另一个类的析构函数。而且编译器向我吐出警告,析构函数将不会被调用。我能做什么?我可以通过创建另一个类,因为我需要的功能,避免了向前声明避免这个问题,不过这不会是教育性我...C++前向声明和析构函数
这是我的第一类Header.h:
#ifndef H_HEADER
#define H_HEADER
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include "DataFiles.h"
class Character; // forward declaration Header <-> Character
class Header {
private:
Character * ch;
};
void cleanUp(std::vector <SDL_Surface*> & Vsurface, std::vector <TTF_Font*> & Vfont, std::vector <Character*> & Vchar);
// ... Other functions use in main.cpp
#endif
这里是Header.cpp:
#include "Header.h"
using namespace std;
void cleanUp(vector <SDL_Surface*> & Vsurface, vector <TTF_Font*> & Vfont, vector <Character*> & Vchar) {
for(unsigned int i(0); i < Vsurface.size(); i++)
SDL_FreeSurface(Vsurface[i]);
for(unsigned int i(0); i < Vfont.size(); i++)
TTF_CloseFont(Vfont[i]);
for(unsigned int i(0); i < Vchar.size(); i++)
delete Vchar[i];
TTF_Quit();
SDL_Quit();
}
这里是其他Character.h类:
#ifndef H_CHARACTER
#define H_CHARACTER
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include </usr/include/SDL/SDL_image.h>
#include </usr/include/SDL/SDL.h>
#include </usr/include/SDL/SDL_ttf.h>
#include "DataFiles.h"
#include "CharFrame.h"
class Header; // Forward declaration Header <-> Character
class Character {
public:
Character(std::string& dataPath);
~Character();
// .. other functions
private:
Header * h;
// ... other attributes
};
#endif
这里是我的性格的析构函数:
Character::~Character() {
cout << "Character " << m_name << " deleted.\n-----------------------------------\n" << endl;
}
所以我的节目结束的时候,我呼吁头的功能“清理()”给它的指针到字符的载体。然后应该通过角色的析构函数删除每个指针〜Character(); 然而编译给了我三次警告:
Header.cpp: In function ‘void cleanUp(std::vector<SDL_Surface*>&, std::vector<_TTF_Font*>&, std::vector<Character*>&)’:
Header.cpp:66:17: warning: possible problem detected in invocation of delete operator: [enabled by default]
Header.cpp:66:17: warning: invalid use of incomplete type ‘struct Character’ [enabled by default]
Header.h:27:7: warning: forward declaration of ‘struct Character’ [enabled by default]
Header.cpp:66:17: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
而且一旦我的程序终止时,人物的析构函数的消息将不会出现,这意味着析构函数显然不叫。
我在做什么毛病向前声明?
您是否在'Header.cpp'中包含了'Character.h'?如果没有,请尝试一下。 – ilent2
没有这会反对声明如何工作。看到cmaster的答案在那里:http://stackoverflow.com/questions/18549134/c-headers-inclusions;) –
cmaster的答案是谈论包括'Header.h'内的'Character.h'(以及为什么你不应该做这个)。但是你最终需要包含'Character.h',以便编译器知道在哪里找到它。 'Header.cpp'里面适当的地方。 – ilent2