在我的程序中使用基本类函数.C++

Using basic class function in my program. C++

本文关键字:类函数 C++ 我的 程序      更新时间:2023-10-16

新人又来了,我又像往常一样被卡住了。(不知道我的问题标题应该是什么,但我认为它肯定与功能有关(我想让用户掷骰子,并在他们达到 20 时达到最大值。但问题是我的函数obj.currentRoll();它没有按照我的预期将以前的滚动相加。基本上,我希望它存储连续轮次value=value+roll;的值,以便以后我可以使用像if (value>max){return 0}或 sth 这样的 if 语句。我能够以更简单的方式做到这一点,而无需使用单独的类或函数,但我希望以这种方式也能达到相同的结果,但失败了。有什么建议吗?

#include <iostream>
#include "myClass.h"
#include <string>
#include <cstdlib>
#include <ctime>

int main()
{
srand(time(0));
std::string rollCh;
const int max=20;

std::cout<<"Your lucky number for the day is " <<1+(rand()%30)<<"n";
std::cout<<"Roll the dice? (Y/N)"<< "n";
std::string ch;
std::cin>>ch;
if(ch=="Y"||ch=="y"){
myClass obj;
do
{
std::cout<<"Rolling...n"<<"n";
std::cout<<"You rolled "; obj.funcRoll();std::cout<<"!!!" <<"n";
std::cout<<"Double checking your roll...yes it is ";obj.funcRoll();
obj.currentRoll();
std::cout<<"nn Roll again? (Y/N)"<<"n";
std::cin>>rollCh;
}
while (rollCh=="Y"||rollCh=="y");
}
return 0;
}

myClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class myClass
{
public:
myClass();
void funcRoll();
int roll;
int value;
void currentRoll();
};
#endif // MYCLASS_H

我的班级.cpp

#include "myClass.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
myClass::myClass()
{}
void myClass:: funcRoll(){
srand(time(0));
roll=1+(rand()%6);
std::cout<<roll;
}
void myClass:: currentRoll(){
value=0;
value=value+roll;
std::cout<<"n You have rolled "<< value<<" so far";
}

我先做的更简单的方法

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
int max=20;
int value=0;
int roll;
std::string ch;
do
{
srand(time(0));
roll=1+(rand()%6);
std::cout<<"nYou rolled "<<roll<<"n";
value=value+roll;
std::cout<<"Your total value = " << value<<"n";
if (value<max){
std::cout<<"continue? nn"<<"n";
std::cin>>ch;}
else {
std::cout<<"You have maxed out. Congrats!"<<"n";
return 0;
}
}
while (ch=="y"||ch=="Y");
return 0;
}

value = 0;语句从currentRoll()函数移动到构造函数:

myClass::myClass() : value(0){}

std::string类型替换为char。cpp.sh 上的活生生的例子。