C++ 在构造函数中使用const创建类实例

C++ 在构造函数中使用const创建类实例,c++,int,constants,C++,Int,Constants,我有一个结构: 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) { currMagazin

我有一个结构:

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中,我不知道如何创建新的Ammo变量并初始化这些常量, 我试过这个:

Ammo gun(10,40);
还有这个

Ammo gun = new Ammo(10,40);
但它们都不起作用。谢谢

编辑:

我还有一个类CPlayer,在这里我创建了弹药对象:

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

    CPlayer() {...}
    ~CPlayer() {...}
    }
但我不能编译它

编辑2--------------------------------------------------- 我已将问题重写到console中:

#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;
}
#包括
结构弹药
{
常量int MAX;
常量int MAX2;
弹药(整数a,整数b):最大(a),最大2(b)
{
}
~Ammo(){}
};
CA类
{
公众:
国际卫生组织;
Ammo-amm(10,10);//错误“需要类型说明符”
Ammo amm2{10,10};//错误“应为a;”
CA(){}
~CA(){}
};
int main()
{
系统(“暂停”);
返回0;
}

问题是如何将Ammo对象添加到类中?

您的第一个示例初始化常量变量。交叉检查:

弹药枪{10,40};

好的,我现在就知道了!我必须在CA类的构造函数中设置Ammo结构的构造函数

class CA
{
public:
    int health;
    Ammo amm;

    CA() : amm(10,100)
    {

        std::cout << "Yeah!" << amm.MAX << " " << amm.MAX2;
    }
    ~CA(){}
};
CA类
{
公众:
国际卫生组织;
弹药;
CA():安培(10100)
{

STD::CUT新创建指针,弹药*不能转换成弹药,所以最后一个例子永远是无效的。另一个是问题,请提供。另外,<代码>弹药枪(10/40);应该是肯定的。第二个肯定会失败,因为C++不是Java.是的。没有人告诉过它。编辑以更好地理解。
class CA
{
public:
    int health;
    Ammo amm;

    CA() : amm(10,100)
    {

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