为什么从派生类访问基类的数据时会返回无意义的数据(我认为是指针数据)

why when accessing data from the base class from a derived class does it return nonsense (pointer data i think)

本文关键字:数据 无意义 指针 认为是 返回 派生 访问 为什么 基类      更新时间:2023-10-16

我正在为一个使用坐标的基于文本的游戏制作一个碰撞检测系统。我正试图找回我的玩家和一系列怪物的x和y位置。坐标保存在低音类Character中。当我试图检索数据时,它返回Xpos-858993460,我假设它是从我使用的指针中混合而来的。

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MON_SIZE = 10;
monster* monArr[MON_SIZE];
player player1;
bool collision();
int main(){
void initialise();
player1.moveChar(3, 6);
bool temp;
temp = collision();
if (temp = true){
    cout << endl << "collision detected" << endl;
}
        system("pause");
        return 0;
}

void initialise()
{
    srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        int inx = rand() % 9;
        int iny = rand() % 9;
        monArr[i] = new monster();
        monArr[i]->moveChar(inx, iny);
    }
}
bool collision()
{
    bool collision;
    for (int i = 0; i < 10; i++)
    {
        int mx, my, px, py;
        monArr[i]->getPos(mx, my);
        player1.getPos(px, py);
        if (mx == px && my == py)
        {
            collision = true;
            cout << endl << mx << " " << my << endl;
        }else collision = false;
    }
    return collision;
}

#pragma once
#include "character.h"
class player :
    public character
{
private:
public:
    player();
    ~player();
};

#pragma once
#include "character.h"
class monster :
    public character
{
public:
    monster();
    ~monster();
private:
};

#include "character.h"
#include <iostream>
using namespace std;
character::character()
{
    xpos = 0;
    ypos = 0;
}

character::~character()
{
}

void character::moveChar(int Xpos, int Ypos)
{
    xpos = Xpos;
    ypos = Ypos;
}
void character::printPos(){
    cout << "Position: " << xpos << " . " << ypos << endl;
}
void character::getPos(int& Xpos, int& Ypos){
    Xpos= xpos;
    Ypos= ypos;
}

#pragma once
class character
{
public:
    character();
    ~character();
    void moveChar(int Xpos, int Ypos);
    void printPos();
    void getPos(int& Xpos, int& Ypos);
protected:
    int xpos;
    int ypos;
};
int main(){
    void initialise();
    ...

上面没有调用函数initialize。虽然您没有发布该函数,但我想它会初始化您的数组和变量。。。改为写入:

int main(){
    initialise();
    ...

并将initialize()的定义移到main之前,或者至少放一个其原型的声明。

将您的charactertoer::getPos函数更改为this:

void character::getPos(int& Xpos, int& Ypos){
    Xpos = xpos;
    Ypos = ypos;
}

语句Xpos*=Xpos等效于Xpos=Xpos*Xpos。这不是你想要的,尤其是因为你的Xpos参数没有初始化。