在我的程序中使用基本类函数.C++
Using basic class function in my program. C++
新人又来了,我又像往常一样被卡住了。(不知道我的问题标题应该是什么,但我认为它肯定与功能有关(我想让用户掷骰子,并在他们达到 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 上的活生生的例子。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 在类函数中初始化外部作用域变量
- c++ 在非类函数中使用类变量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 从类成员函数到类 C 函数指针的转换
- 如何在模板类函数中分配结构值?
- 有没有办法将重载的类函数绑定到函数对象?
- 启动类函数作为失去引用的线程
- C++调用使用重写函数的父类函数
- 将值传递到另一个类函数在打印时为零
- 计算对类函数的所有调用次数
- 由于签名差异,调用了错误的子类函数
- 使用宏调用类函数
- 虚拟基类函数中派生类的大小
- 模板类/函数中的交叉前向声明
- 在C++中使用非静态类函数的函数
- 无法访问基类函数 C++
- 类函数返回到另一个类函数返回打印不同的值
- C++ 在外部使用嵌套结构实现类函数