无法访问类的成员

时间:2011-11-11 18:07:06

标签: c++ class

我有一点问题,我可能错误地包含了类文件,因为我无法访问敌人类的成员。我究竟做错了什么? 我的班级

#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
}

2 个答案:

答案 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(){
    //....
}
//....

答案 1 :(得分:3)

除了弗拉德的回答之外,你的文件与main对Enemy类没有任何了解,除了它存在。

一般情况下,声明类位于标题文件中,函数定义放入另一个。

考虑拆分文件,如:

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;}
相关问题