我在做一个骰子游戏。我正在构建这些文件,但得到了以下错误:
没有调用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;
}发布于 2013-11-19 23:32:44
我发现代码有几个问题。以下是我的解决办法和建议:
首先,您对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只需要做一次,而不是每次点名时--也许在主要功能中:
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;
};
#endifDice.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));
}希望这是一个好的起点。玩得开心点!
https://stackoverflow.com/questions/20083748
复制相似问题