2016-02-28 110 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); 
}