c__app.exe已停止工作?

时间:2016-02-28 02:52:57

标签: c++

我是用c++编写的简单应用程序(只是学习)但我的应用程序运行不正常。这是我的代码:

的main.cpp

#include <iostream>
#include <cstdio>
#include "Player.h"

using namespace std;

int main() {
    Player p1("Anish");
    Player p2("ASK");
    cout << "Game starts." << endl;
    cout << p1.getPlayerName() << " has " << p1.getHitPoint() << " hitpoints." << endl;
    cout << p2.getPlayerName() << " has " << p2.getHitPoint() << " hitpoints." << endl;
    p1.hit(&p2);

   // cout << p2.getHitPoint();
    cout << p1.getPlayerName() << " hits " << p2.getPlayerName() << endl;
    cout << p1.getPlayerName() << " has " << p1.getHitPoint() << " hitpoints." << endl;
    cout << p2.getPlayerName() << " has " << p2.getHitPoint() << " hitpoints." << endl;
    p1.heal(&p2);
    cout << p1.getPlayerName() << " heals " << p2.getPlayerName() << endl;
    cout << p1.getPlayerName() << " has " << p1.getHitPoint() << " hitpoints." << endl;
    cout << p2.getPlayerName() << " has " << p2.getHitPoint() << " hitpoints." << endl;
    return 0;
}

Player.cpp

#include "Player.h"

Player::Player(string name) {
    playerName=name;
    setHitPoint(100);
}

void Player::setHitPoint(int points){
    hitPoint=points;
}

Player Player::hit(Player* p){
    Player player=*p;
    int point=player.getHitPoint()-10;
    player.setHitPoint(point);
}

Player Player::heal(Player* p){
    Player player=*p;
    player.setHitPoint(player.getHitPoint()+5);
}

Player.h

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

#ifndef PLAYER_H
#define PLAYER_H

class Player {
public:
    Player(string);
    Player hit(Player*);
    Player heal(Player*);
    void setHitPoint(int);
    int getHitPoint() {return hitPoint;};
    string getPlayerName() {return playerName;};
private:
    string playerName;
    int hitPoint;
};

#endif  /* PLAYER_H */

这些代码提供以下输出: 构建

Game starts.
Anish has 100 hitpoints.
ASK has 100 hitpoints.

RUN FAILED (exit value -1,073,741,819, total time: 2s)

停止工作。 任何人都可以对这个问题有所了解吗?我也没有收到任何错误。

1 个答案:

答案 0 :(得分:1)

我开始修理这些:

Player Player::hit(Player* p){
    Player player=*p;
    int point=player.getHitPoint()-10;
    player.setHitPoint(point);
}

Player Player::heal(Player* p){
    Player player=*p;
    player.setHitPoint(player.getHitPoint()+5);
}

您实际上正在复制传入的播放器.C ++与Java不同,其中所有内容都是对象/指针/引用。 C ++喜欢复制东西。 &#34;玩家玩家= * p&#34;说&#34;制作p指向的副本并将其放入播放器。&#34;

然后,你的函数说它将返回一个Player,但它什么也没有返回。编译器是核心转储,因为它试图破坏不存在的东西。 (我有点惊讶你的编译器没有给你一个错误。)

试试这些:

void Player::hit(Player* p){
    int point=p->getHitPoint()-10;
    p->setHitPoint(point);
}

void Player::heal(Player* p){
    p->setHitPoint(p->getHitPoint()+5);
}