C++ C++;如何创建两个分别显示随机数10次的对象?
我试图编写的程序是创建两个对象,分别显示1000-9000和100-900之间的随机数 我试图写我的第一个C++程序,它使用类和多个文件,但有问题。我在main()函数的for循环中得到错误;它表示在“R”和“问题”之前预期的主要表达式C++ C++;如何创建两个分别显示随机数10次的对象?,c++,class,random,numbers,generator,C++,Class,Random,Numbers,Generator,我试图编写的程序是创建两个对象,分别显示1000-9000和100-900之间的随机数 我试图写我的第一个C++程序,它使用类和多个文件,但有问题。我在main()函数的for循环中得到错误;它表示在“R”和“问题”之前预期的主要表达式 不能在表达式的中间声明变量,以下都是错误的。 cout << RandomNum four(1000,9000); << endl; 语法错误与标题中的任何内容无关。再(仔细地)读一遍,然后把它修好。RandomNum-four(10
不能在表达式的中间声明变量,以下都是错误的。
cout << RandomNum four(1000,9000); << endl;
语法错误与标题中的任何内容无关。再(仔细地)读一遍,然后把它修好。
RandomNum-four(10009000)
应该做什么?在什么背景下?谢谢你的意见这更有意义吗?我现在明白了:)。要为每个对象创建10,我将包含for循环以迭代到10。为了完整性,您实际上可以“内联”创建对象,但通常不建议这样做,因为您的代码更难阅读,您正在创建并丢弃对象,而不是以后可能再重用它(这并不坏,因为您的类在这里很轻):cout
#ifndef RANDOM_H
#define RANDOM_H
class RandomNum
{
public:
RandomNum(int ix, int iy);
int operator ()();
int operator ()(int ny);
int operator ()(int nx, int ny);
int x,y;
};
#endif
#include <iostream>
#include "randomInt.h"
#include <cstdlib>
using namespace std;
RandomInt::RandomInt(int ix, int iy):x(ix), y(iy)
{}
int RandomInt::operator()()
{
return x + rand() % (y - x + 1);
}
int RandomInt::operator()(int ny)
{
return x + rand() % (ny - x + 1);
}
int RandomInt::operator()(int nx, int ny)
{
return nx + rand() % (ny - nx + 1);
}
cout << RandomNum four(1000,9000); << endl;
cout << RandomNum three(100,900); << endl;
RandomNum four (1000,9000); // declaration of `four`
RandomNum three (100, 900); // declaration of `three`
cout << four () << endl;
cout << three () << endl;