2017-06-01 94 views
1

我是C++的新手,我必須創建一個簡單的視頻遊戲,它有一個敵人級別,當我嘗試從主.cpp,創建enemy.h和enemy.cpp,我按照我在互聯網上看到的所有指示,但它不斷向我顯示錯誤信息,我希望你們能幫助我。我需要幫助分離C++ LNK2005和LNK1169中的類代碼

enemy.cpp文件

#include "enemy.h" 

enemy::enemy(int _hp, int _attackValue, string _name) { 
    hp = _hp; 
    attackValue = _attackValue; 
    name = _name; 
} 

void enemy::attack(enemy agressor, enemy objective) { 
    objective.set_hp(objective.hp - agressor.attackValue); 
    objective.showinfo(objective, 2); 
} 

void enemy::showinfo(enemy enemy, int hero) { 
    if (hero == 1) { 
     cout << "  \n\n\n\n\n\n\n"; 
     cout << enemy.name; 
     cout << "  \n\n\n\n\n\n\n\n"; 
     for (int i = enemy.hp/5; i > 0; i--) { 
      cout << "|"; 
     } 
     cout << "  \n\n\n\n\n\n\n\n\n"; 
     cout << enemy.hp; 
    } 
    else { 
     cout << "         \n\n\n\n\n\n\n"; 
     cout << enemy.name; 
     cout << "         \n\n\n\n\n\n\n\n"; 
     for (int i = enemy.hp/5; i > 0; i--) { 
      cout << "|"; 
     } 
     cout << "         \n\n\n\n\n\n\n\n\n"; 
     cout << enemy.hp; 
    } 
} 

int enemy::get_hp() { 
    return hp; 
} 

void enemy::set_hp(int _hp) { 
    hp = _hp; 
} 

int enemy::get_attackValue() { 
    return attackValue; 
} 

string enemy::get_name() { 
    return name; 
} 

enemy.h文件

#pragma once 

#ifndef enemy_H 
#define enemy_H 

class enemy { 

private: 

    int hp, attackValue; 
    string name; 
public: 
    enemy(); 
    enemy(int, int, string); 
    void attack(enemy, enemy); 
    void showinfo(enemy, int); 
    int get_hp(); 
    void set_hp(int hp); 
    int get_attackValue(); 
    string get_name(); 
}; 

#endif // !enemy_H 

PD:我還是不知道如何實現setcursorposition在C++中,你可以看到。

回答

0

您已聲明enemy()但尚未定義它。如果你聲明瞭默認的構造函數,確保你定義它(可能在你的.cpp文件中)

0

error that you get表示你違反了ODR (one definition rule)。換句話說,當你試圖將你的enemy類從你的主體中分離出來時,你並沒有將所有部分從那裏遠程傳遞,而是以多個cpp文件中的相同代碼結束。作爲一個側面說明,看起來你忘了定義你的enemy :: enemy()構造函數,或忘記將它從main.cpp移動到enemy.cpp?