简体   繁体   English

无法访问类的成员

[英]Cannot access members of a class

I have a little problem, i probably included the class files wrongly, since i can't acces members of the enemy class. 我有一点问题,我可能错误地包含了类文件,因为我无法访问敌人类的成员。 What am i doing wrong? 我究竟做错了什么? my cpp for 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;
}

Enemy()
{

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

my header for class: 我的标题:

class Enemy;

my main: 我的主要:

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

Your main file will only see what you wrote in the header, which is that Enemy is a class. 你的主文件只能看到你在标题中写的内容,即Enemy是一个类。 Normally, you'd declare your whole class with fields and method signatures in the header files, and provide implementations in the .cpp file. 通常,您将在头文件中使用字段和方法签名声明整个类,并在.cpp文件中提供实现。

classes.h : 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 : classes.cpp

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

In addition to Vlad's answer, your file with main doesn't know anything about the Enemy class, other than that it exists. 除了弗拉德的答案之外,你的文件与main对Enemy类没有任何了解,除了它存在。

In general, the class declarations goes in the header file, and the function definitions go in another. 通常,类声明在头文件中,而函数定义在另一个中。

Consider splitting the files like: 考虑拆分文件,如:

classes.h: 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

Note the "include guards" which prevent the same file from being included more than once. 请注意“包含防护”,它可以防止同一文件被多次包含。 Good practice to use on header files, or else you get annoying compilation errors. 在头文件上使用的好习惯,否则你会遇到烦人的编译错误。

classes.cpp: 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;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM