[英]Copy constructor doesn't recognize inherited members
我有兩節課:
class entity {
public:
SDL_Rect pos;
float x;
float y;
std::string spriteFile;
SDL_Surface * spriteHandle;
int rePos (int newX, int newY);
int move (float deltaX, float deltaY, bool check); // Move x & y the specified amounts, also moving pos.x and pos.y for every integer increase of x or y
int display (SDL_Surface * screenSurface); //Use SDL_BlipSurface to blip the image to the screen
int loadImage (SDL_PixelFormat * format); //Load the image using the spriteFile string and optimize it using the SDL_PixelFormat of the Screen
entity (std::string file, int w, int h);
entity () {};
~entity () { SDL_FreeSurface(spriteHandle);}
entity (const entity &old) : pos(old.pos), x(old.x), y(old.y), spriteFile(old.spriteFile) {
spriteHandle = new SDL_Surface(*spriteHandle);
}
};
class multiEntity: public entity {
/*
Use multiEntity rather than entity when multiple images need to be blipped to different
positions.
*/
private:
static std::vector<stringBoolPair> deconstructed;
public:
std::string entType;
multiEntity (std::string file, int w, int h, std::string enttype) {
entity(file, w, h);
entType = enttype;
bool found = false;
for (int i = 0; i < deconstructed.size(); i++) {
found = (enttype == deconstructed[i].str);
}
if (found) deconstructed.emplace_back(enttype, false);
}
multiEntity (const multiEntity& old) :
spriteFile(old.spriteFile),
x(old.x),
y(old.y),
spriteHandle(old.spriteHandle),
pos(old.pos),
entType(old.entType) {}
~multiEntity () {
for (int i = 0; i < deconstructed.size(); i++) {
if (deconstructed[i].str == entType) {
SDL_FreeSurface(spriteHandle);
deconstructed[i].Bool = true;
}
}
}
multiEntity& operator= (const multiEntity& old) {
spriteFile = old.spriteFile;
pos = old.pos;
x = old.x;
y = old.y;
entType = old.entType;
spriteHandle = old.spriteHandle;
return *this;
}
};
當我嘗試編譯包含此代碼的代碼時,收到一條錯誤消息,指出class multiEntity does not have any field named 'pos'
。 復制構造函數中除entType
之外的所有變量都會發生這種情況。 我試圖做的是使用相同的SDL_Surface擁有一個vector entity
。 因此,我覺得我應該創建一個單獨的類,其中每個具有相同entType
對象的spriteHandle
都具有相同的值。 這應該指向同一張圖片,當我有75個實例的圖片實例想在屏幕上顯示時,這是最有用的。 我想使用vector的構造函數布局,以便將信息復制過來,而不是每次都創建一個新的指針。
您不能在派生類的副本構造函數中初始化基類的成員。 它們應該通過基類的副本構造函數進行初始化。 您應該只在成員初始化列表中調用它:
multiEntity (const multiEntity& old) :
entity(old), // initialize entity's members via entity::entity(const entity&)
entType(old.entType) // initialize multiEntity's member entType
{}
如果基類的復制構造函數的行為不是您想要的,則可以在派生類的構造函數主體中進行一些分配,例如
multiEntity (const multiEntity& old) :
// nothing specified, same as write entity() here
// entity's members will be initialized via entity::entity()
entType(old.entType) // initialize multiEntity's member entType
{
// perform assignment here
spriteFile = old.spriteFile;
x = old.x;
y = old.y;
spriteHandle = old.spriteHandle;
pos = old.pos;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.