2015-04-17 40 views
-4

與常量創建類的實例我有結構:在構造

struct Ammo 
{ 
public: 
    const int MAX_MAGAZINES; 
    const int MAX_IN_MAGAZINE; 
    int currMagazineAmmo; 
    int totalAmmo; 
    Ammo(int maxMag, int maxMagAmmo) : MAX_MAGAZINES(maxMag), MAX_IN_MAGAZINE(maxMagAmmo) 
    { 
     currMagazineAmmo = totalAmmo = 0; 
    } 
    ~Ammo() 
    { 

    } 
    bool MagazineNotEmpty() {return currMagazineAmmo > 0;} 
    bool NotEmpty() {return totalAmmo > 0;} 
}; 

,並在我的cpp我不知道如何使新的彈藥變量並初始化這些consts, 我嘗試這樣做:

Ammo gun(10,40); 

和這

Ammo gun = new Ammo(10,40); 

但他們都沒有工作。由於

編輯:

我也有類CPlayer其中i創建彈藥對象:

class CPlayer 
    { 
    public: 
    //... 
    Ammo gun{10,40};//there is error 
    Ammo bow(10,40);//also error 'expected a type specifier' 

    CPlayer() {...} 
    ~CPlayer() {...} 
    } 

,但我不能編譯。

EDIT2 --------------------------------------------- ------ 我已經重寫這個問題到控制檯:

#include <iostream> 

struct Ammo 
{ 
    const int MAX; 
    const int MAX2; 

    Ammo(int a, int b) : MAX(a), MAX2(b) 
    { 

    } 
    ~Ammo() {} 
}; 

class CA 
{ 
public: 
    int health; 
      Ammo amm(10,10);//error 'expected a type specifier' 
    Ammo amm2{10,10};//error 'expected a ;' 

    CA(){} 
    ~CA(){} 
}; 

int main() 
{ 
    system("pause"); 
    return 0; 
} 

的問題是如何彈藥對象添加到一個類?

+0

新建的指針,彈藥*不能轉換成彈藥,所以最後一個例子永遠不會有效。另一個是http://en.wikipedia.org/wiki/Most_vexing_parse問題 – Creris

+1

請提供[MCVE](http://www.stackoverflow.com/help/mcve)。另外,「彈藥槍(10,40)」絕對有效。第二個應該肯定會失敗,因爲C++不是Java。 – Barry

回答

0

好的我現在明白了!我不得不在CA類的構造函數中設置Ammo結構的構造函數。

class CA 
{ 
public: 
    int health; 
    Ammo amm; 

    CA() : amm(10,100) 
    { 

     std::cout << "Yeah!" << amm.MAX << " " << amm.MAX2; 
    } 
    ~CA(){} 
}; 
0

你的第一個例子初始化const變量。 Crosscheck:http://ideone.com/M55Mls

Ammo gun{10,40}; 
std::cout << gun.MAX_MAGAZINES; 

第二個不應該編譯。你不能將彈藥分配給彈藥*。檢查什麼operator new返回。請熟悉智能指針。手動內存分配不再推薦在C++中使用。

最令人頭痛的解析權沒有問題。爲了避免將來最棘手的解析問題,請使用C++ 11的統一括號初始化:Ammo gun{10,40};

+0

是的。沒有人告訴過有一個。爲了更好的理解而編輯。 – CyberGuy