C++ 无法访问类的成员

C++ 无法访问类的成员,c++,class,C++,Class,我有一个小问题,我可能错误地包含了类文件,因为我无法访问敌人类的成员。我做错了什么? 我上课的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; }

我有一个小问题,我可能错误地包含了类文件,因为我无法访问敌人类的成员。我做错了什么? 我上课的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
}

您的主文件将只看到您在标题中写的内容,即
敌方
是一个类。通常,您会在头文件中用字段和方法签名声明整个类,并在.cpp文件中提供实现

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

除了Vlad的回答,你在main中的文件除了它的存在之外,对敌人类一无所知

一般来说,类声明放在头文件中,函数定义放在另一个头文件中

考虑像这样拆分文件:

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

没有数据成员还是说也没有函数成员?我也不能访问setPosX(),我用struct试过了,没有效果。我的错。起初我以为您指的是字段。所以所有变量通常都会在其类中指向.h文件,而函数则指向一个单独的cpp文件?通常是这样,但也存在静态字段(请参阅)以及内联和模板函数的问题。