簡體   English   中英

聲明一個 C++ 類

[英]Declaring a Class C++

我正在努力知道如何創建一個類。 我想創建一個“玩家”類,我想要做的就是傳入名稱,而我會讓其他變量從 0 開始,直到它們在游戲運行時更新(稍后在程序中)

Player::Player(string name_in)    
{
    name = name_in;
    int numOfWins = 0;
    int numOfLoses = 0;
    int numOfDraws = 0;
    int totalMatches = 0;
}

現在有很多關於 numOfWins、numOfLoses、numOfDraws 和 totalMatches 的錯誤。 我能做些什么來解決這個問題?

也許錯誤出在你的int ...部分賦值中,它本質上在構造函數中創建了一個新的局部變量。

試試這個版本:

#include <string>
using namespace std;

class Player
{
    string name;
    int numOfWins;
    int numOfLoses;
    int numOfDraws;
    int totalMatches;

public:
    Player(string name_in)    
    {
        name = name_in;
        numOfWins = 0;
        numOfLoses = 0;
        numOfDraws = 0;
        totalMatches = 0;
    }
};

你得到的錯誤,至少從你發布的片段中得到是因為你不能在構造函數中聲明變量 - 你在類體中聲明它們並在構造函數中初始化或使用另一個函數。

#include <string>

class Player {
public:
    Player( std::string const& name_in) : name( name_in),
                                          numOfWins(), numOfLoses(),
                                          numOfDraws(), totalMatches()
                                          {}  // constructor 
                                              // will initialize variables
                                              // numOfWins() means default 
                                              // initialization of an integer
private:
    std::string name;
    int numOfWins;
    int numOfLoses;
    int numOfDraws;
    int totalMatches;
};

用法:

int main() {
    Player( "player_one");
    return 0;
}

您應該在類聲明中聲明其他實例變量,而不是將它們聲明為局部變量(這是完全沒用的)。

// This part goes in the header
class Player {
    string name;
    int numOfWins;
    int numOfLoses;
    int numOfDraws;
    int totalMatches;
public:
    Player(string name_in);
};

現在在構造函數中,您可以使用初始化列表:

// This part goes into the CPP file
Player::Player(string name_in)
// Initialization list precedes the body of the constructor
: name(name_in), numOfWins(0), numOfLoses(0), numOfDraws(0), totalMatches(0) {
// In this case, the body of the constructor is empty;
// there are no local variable declarations here.
}

有點含糊,但我會嘗試一下。 你可能想要:

class Player{
    string name;    
    int numOfWins;
    int numOfLosses;
    int numOfDraws;
    int totalMatches;
    Player(string name_in)
};

Player::Player(string name_in){
    name = name_in;
    numOfWins = 0;
    numOfLosses = 0;
    numOfDraws = 0;
    totalMatches = 0;
}

有一段時間沒有使用 C++,所以這可能是錯誤的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM