[英]No matching function for call to Dice::Dice (class constructor)
我正在創建一個骰子游戲。 我正在構建文件,但得到以下錯誤:
沒有用於調用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;
}
我看到代碼有幾個問題。 這是我的修復和提示:
首先, 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
。 為什么不嘗試一些面向對象而不是函數庫類。 想想一個真正的骰子對象! 這是一個骰子抽象開始:
#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;
}
#ifndef DICE_H
#define DICE_H
class Dice
{
public:
Dice(int sides);
int getRoll();
static void randomize(); // Call only once
private:
int sides;
};
#endif
#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));
}
希望這是一個很好的起點。 玩得很開心!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.