【问题标题】:error C2512 no appropriate default constructor available错误 C2512 没有合适的默认构造函数可用
【发布时间】:2013-08-25 19:48:34
【问题描述】:

好的,所以我遇到了这个涉及两个类的问题。

骰子.h:

#pragma once

#include <random>

using std::random_device;
using std::uniform_int_distribution;

class Dice
{
public:
    Dice(int Sides);
    int roll(void);

protected:
    int nSides;
    random_device generator;
    uniform_int_distribution<int> distribution;
};

骰子.cpp:

#include "Dice.h"



Dice::Dice(int Sides)
{
    nSides=Sides;
}



int Dice::roll(void)
{
    random_device generator;
    uniform_int_distribution<int> distribution(1,nSides);

    return distribution(generator);
}

DmgCalc.h:

#pragma once

#include "CharSheet.h"
#include "Dice.h"
class DmgCalc
{
public:
    DmgCalc(CharSheet P1, CharSheet P2);

    bool Dodge();

    int Attack();

    int Roll();
protected:

    int nP1Con, nP1Str, nP1Dex;
    int nP2Con, nP2Dex, nP2Hlth;

    Dice d6;
};

DmgCalc.cpp:

#include "DmgCalc.h"


DmgCalc::DmgCalc(CharSheet P1, CharSheet P2)
{
    nP1Str=P1.getStr();
    nP1Dex=P1.getDex();

    nP2Con=P2.getCon();
    nP2Dex=P2.getDex();
    nP2Hlth=P2.getHlth();

    Dice d6(6);
}


bool DmgCalc::Dodge()
{
    return ((nP1Dex + d6.roll())-(nP2Dex + d6.roll()) > 0);
}

int DmgCalc::Attack()
{
    nP2Hlth-=((nP1Str + d6.roll())-(nP2Con));

    return nP2Hlth;
}

int DmgCalc::Roll()
{
    return d6.roll();
}

每当我尝试编译时都会收到此错误:

Error   2   error C2512: 'Dice' : no appropriate default constructor available

如果我使用void Dice(void); 格式为 Dice 创建另一个构造函数,它就可以正常工作。

任何帮助将不胜感激

【问题讨论】:

  • 我在这里没有看到任何试图使用它的东西,但我确实在构造函数中看到了一个应该是数据成员的局部变量。
  • 这不是问题,但数据成员通常是private,而不是protected

标签: c++


【解决方案1】:

您需要在构造函数的初始化列表中初始化Dice 成员

DmgCalc::DmgCalc(CharSheet P1, CharSheet P2)
    : d6(20)
{

此处未初始化的任何内容都将调用其默认构造函数。 Dice 没有默认构造函数,因此编译器出错。

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 2012-10-10
    • 2014-12-31
    • 2012-12-16
    • 2014-01-31
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多