2011-11-11 49 views
2

我有一個小問題,我可能錯誤地包含了類文件,因爲我無法訪問敵人類的成員。我究竟做錯了什麼? 我CPP類無法訪問類的成員

#include "classes.h" 

class Enemy 
{ 
bool alive; 
double posX,posY; 
int enemyNum; 
int animframe; 
public: 
Enemy(int col,int row) 
{ 
    animframe = rand() % 2; 
    posX = col*50; 
    posY = row*50; 
} 

Enemy() 
{ 

} 
void destroy() 
{ 
    alive = 0; 
} 
void setposX(double x) 
{x = posX;} 
void setposY(double y) 
{y = posY;} 
}; 

我的頭類:

class Enemy; 

我的主:

#include "classes.h" 
Enemy alien; 
int main() 
{ 
    alien. // this is where intelisense tells me there are no members 
} 
+0

沒有數據成員或你的意思是沒有作用的成員呢? –

回答

6

你的主要文件將只看到你在標題中寫道,這是Enemy是一類。通常情況下,你需要在頭文件中聲明整個類的字段和方法簽名,並在.cpp文件中提供實現。

classes.h

#ifndef _CLASSES_H_ 
#define _CLASSES_H_ 
class Enemy 
{ 
    bool alive; 
    double posX,posY; 
    int enemyNum; 
    int animframe; 
public: 
    Enemy(int col,int row); 
    Enemy(); 
    void destroy(); 
    void setposX(double x); 
    void setposY(double y); 
}; 
#endif 

classes.cpp

#include "classes.h" 
//.... 
void Enemy::destroy(){ 
    //.... 
} 
//.... 
+0

我也不能訪問setPosX(),我試過它與結構,沒有效果。 –

+0

我的不好。起初我以爲你是指田野。 – Vlad

+0

@coolbartek:Vlad更正了答案 –

3

除了弗拉德的答案,與主文件不知道敵人什麼類,除此之外它存在。

一般來說,類聲明去頭文件中,並在函數定義去另一個。

考慮拆分的文件,比如:

classes.h:

#ifndef CLASSES_H 
#define CLASSES_H 

class Enemy 
{ 
private: 
    bool alive; 
    double posX,posY; 
    int enemyNum; 
    int animframe; 
public: 
    Enemy(int col,int row); 
    Enemy(); 
    void destroy(); 
    void setposX(double x); 
    void setposY(double y); 
}; 

#endif//CLASSES_H 

注意「包括衛士」,這避免相同文件被包含不止一次。在頭文件上使用的好習慣,否則你會遇到煩人的編譯錯誤。

classes.cpp:

#include "classes.h" 

Enemy::Enemy(int col,int row) 
{ 
    animframe = rand() % 2; 
    posX = col*50; 
    posY = row*50; 
} 

Enemy::Enemy() 
{ 

} 

void Enemy::destroy() 
{ 
    alive = 0; 
} 

void Enemy::setposX(double x) {x = posX;} 
void Enemy::setposY(double y) {y = posY;}