调用Dice :: Dice(类构造函数)没有匹配函数

时间:2013-11-19 22:46:13

标签: c++

我正在创建一个骰子游戏。我正在构建文件但出现以下错误:

  

没有匹配函数来调用Dice :: Dice

的main.cpp

#include "Dice.h"
#include <iostream>
using namespace std;

int main (){
    Dice d(1,6);
    cout << d.getRoll() << endl;

    return 0;
}

Dice.h

#ifndef DICE_H
#define DICE_H

class Dice
{
public:
    Dice();
    void getRoll(int m, int n);
};

#endif 

Dice.cpp

#include "Dice.h"
#include <ctime>
#include <iostream>
using namespace std;

Dice::Dice()
{}

void Dice::getRoll(int m, int n) {
    srand(time(0));
    (rand() % n)+m;
}

1 个答案:

答案 0 :(得分:3)

我发现代码有几个问题。以下是我的修复和提示:

首先,Dice的构造和方法调用将无法编译:

Dice d(1,6);                  // you give arguments to the constructor
cout << d.getRoll() << endl;  // your method call has no arguments

但你定义了:

Dice();                       // constructor takes no arguments
void getRoll(int m, int n);   // method takes arguments

其次,srand只需要完成一次,而不是每次调用roll时 - 可能在main函数中:

srand( (unsigned)time( NULL ) );

这会使发生器播种,这样每次程序运行时都应该得到不同的随机数。在第一次掷骰子之前,只召唤一次。

第三,你的getRoll函数什么都不返回,这意味着你没有得到任何价值。您应该根据它们在现实或您的规范中表达的想法来命名变量:

int Dice::getRoll(int maxEyes) {     // Still no good abstraction
    (rand() % maxEyes) + 1;
}

真实骰子在运行时不会更改其maxEyes。为什么不尝试一些面向对象而不是函数库类。想想一个真正的骰子对象!这是一个骰子抽象开始:

的main.cpp

#include "Dice.h"

#include <iostream>

using namespace std;

int main()
{
    Dice::randomize(); // Try commenting this out and run the program several times, check the result, then comment it back in

    Dice diceWith6Sides(6);
    cout << "The 6 sided dice rolls a " << diceWith6Sides.getRoll() << endl;
    cout << "The 6 sided dice rolls a " << diceWith6Sides.getRoll() << endl;
    cout << "The 6 sided dice rolls a " << diceWith6Sides.getRoll() << endl;

    Dice diceWith20Sides(20);
    cout << "The 20 sided dice rolls a " << diceWith20Sides.getRoll() << endl;
    cout << "The 20 sided dice rolls a " << diceWith20Sides.getRoll() << endl;
    cout << "The 20 sided dice rolls a " << diceWith20Sides.getRoll() << endl;
    return 0;
}

Dice.h

#ifndef DICE_H
#define DICE_H

class Dice
{
public:
    Dice(int sides);
    int getRoll();

    static void randomize(); // Call only once

private:
    int sides;
};

#endif

Dice.cpp

#include "Dice.h"

#include <time.h>
#include <stdlib.h>

Dice::Dice(int sides) :
    sides(sides)
{

}

int Dice::getRoll()
{
    return ((rand() % sides) + 1);
}

void Dice::randomize()
{
    srand((unsigned)time(NULL));
}

希望这是一个很好的起点。有很多乐趣!

相关问题