在构造函数中使用 const 创建 class 实例

Creating class instance with const in constructor

我有结构:

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);

但其中 none 有效。谢谢

编辑:

我还有 class CPlayer,我在其中创建了 Ammo 对象:

    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;
}

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

您的第一个示例初始化常量变量。交叉检查:http://ideone.com/M55Mls

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

第二个不应该编译。您不能将 Ammo 分配给 Ammo*。检查什么 operator new returns。请熟悉智能指针。不再建议在 c++ 中手动分配内存。

大多数烦人的解析都没有问题,对不对。为避免将来出现最烦人的解析问题,请使用 c++11 中的统一大括号初始化:Ammo gun{10,40};

好的,我明白了!我必须在 CA class.

的构造函数中设置 Ammo 结构的构造函数
class CA
{
public:
    int health;
    Ammo amm;

    CA() : amm(10,100)
    {

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