繁体   English   中英

方法中不允许访问结构指针

[英]Access to a struct pointer is not permitted in a method

所以我只是在制作一个快速游戏来帮助我理解 C++ 编程。 基本上,我在 main 方法中创建了一个指向名为 player1 的结构体的指针。 在我初始化它并给它一些内存使用后,我决定创建一个方法来显示这个特定指针的值。 现在我认为这只是表明也许我不像我应该理解的指针但是当我尝试访问我在 main 中创建的指针时它不存在。 在代码中,我应该能够输入 player1->health 以获取方法中的健康状况,但 player1 不存在于方法范围内。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef struct enemy{
    char name[120];
    float health;
    int magic;
    int level;


} ene;

typedef struct player{
    char name[120];
    float health;
    int magic;
    int level;
    int exp;


} play;

void startGame();
void saveGame();
void displayHud();



int main(int argc, const char * argv[]) {
    // insert code here...
    // check if there is a save game
    // check if save game

    // initailize the player with 100 health and magic
    play *player1;

    player1 = (play *) malloc(sizeof(play));

    player1->health = 100;
    player1->level = 0;
    player1->magic = 100;
    displayHud();




    startGame();



    free(player1);
    return 0;
}



void displayHud(){
    printf("Health: %d Magic: %d Exp: %d", player1->health); //Doesn't exist


}

您的代码是 C,而不是 C++。

编译器是对的, player1只存在于主函数中。 如果要在displayHud访问它, displayHud必须将其作为参数传递。

这与指针完全没有关系,它只是适用于 C(和 C++)中所有变量的正常规则。

做这个

void displayHud(play *player);

int main(int argc, const char * argv[]) {
    play *player1;
    ...
    displayHud(player1);
    ...
}

void displayHud(play *player) {
    printf("Health: %d Magic: %d Exp: %d", player->health);
}

这是非常基本的东西,你可能应该读一本好书。

暂无
暂无

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

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