2016-02-28 107 views
0

我有一个简单的应用程序写在c++(只是学习),但我的应用程序无法正常运行。这里是我的代码:c__app.exe已停止工作?

的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 */ 

帖E码提供以下的输出: 构建

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

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

并停止工作。 任何人都可以提出一个关于这个问题的想法吗?我也没有得到任何错误。

回答

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++喜欢制作事物的副本。 “Player player = * p”表示“复制p指向的内容并将其放入播放器中。”

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

尝试这些:

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

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