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

时间:2015-04-17 21:01:03

标签: c++ int const

我有结构:

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变量并初始化这些consts, 我试过这个:

Ammo gun(10,40);

和这个

Ammo gun = new Ammo(10,40);

但它们都不起作用。感谢

编辑:

我还有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对象添加到类中?

2 个答案:

答案 0 :(得分:0)

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

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

第二个不应该编译。你不能将Ammo分配给Ammo *。检查operator new返回的内容。请熟悉智能指针。不再推荐在c ++中手动分配内存。

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

答案 1 :(得分:0)

好的,我现在明白了!我必须在CA类的构造函数中设置Ammo结构的构造函数。

class CA
{
public:
    int health;
    Ammo amm;

    CA() : amm(10,100)
    {

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