首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有调用Dice::Dice (类构造函数)的匹配函数

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

Stack Overflow用户
提问于 2013-11-19 22:46:13
回答 1查看 386关注 0票数 1

我在做一个骰子游戏。我正在构建这些文件,但得到了以下错误:

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

main.cpp

代码语言:javascript
复制
#include "Dice.h"
#include <iostream>
using namespace std;

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

    return 0;
}

Dice.h

代码语言:javascript
复制
#ifndef DICE_H
#define DICE_H

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

#endif 

Dice.cpp

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-11-19 23:32:44

我发现代码有几个问题。以下是我的解决办法和建议:

首先,您对Dice的构造和方法调用不会编译:

代码语言:javascript
复制
Dice d(1,6);                  // you give arguments to the constructor
cout << d.getRoll() << endl;  // your method call has no arguments

但你定义:

代码语言:javascript
复制
Dice();                       // constructor takes no arguments
void getRoll(int m, int n);   // method takes arguments

第二,srand只需要做一次,而不是每次点名时--也许在主要功能中:

代码语言:javascript
复制
srand( (unsigned)time( NULL ) );

这是生成器的种子,所以每次程序运行时,你都会得到不同的随机数。只叫一次,在第一次掷骰子之前。

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

代码语言:javascript
复制
int Dice::getRoll(int maxEyes) {     // Still no good abstraction
    (rand() % maxEyes) + 1;
}

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

main.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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));
}

希望这是一个好的起点。玩得开心点!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20083748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档