【问题标题】:C++ How to create two seperate objects that display random numbers 10 times?C ++如何创建两个显示随机数10次的单独对象?
【发布时间】:2014-06-07 05:01:05
【问题描述】:

我正在尝试编写的程序是创建两个对象来分别显示 1000-9000 和 100-900 之间的随机数。

我正在尝试编写我的第一个使用类和多个文件但有问题的 C++ 程序。我在 main() 函数的 for 循环中遇到错误;它在“R”之前表示预期的主表达式,第二个 for 循环也表示“

感谢任何帮助或指导:)

main.cpp:

#include <iostream>
#include "Random.h"
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
  srand(time(0));


  for(int i = 0; i < 10; ++i)
  {
      cout << RandomNum four(1000,9000); << endl;
  }

  for(int i = 0; i < 10; ++i)
  {
      cout << RandomNum three(100,900); << endl;
  }
}

随机.h:

#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

randomNum.cpp:

#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);
}

【问题讨论】:

  • 语法错误与标题中的任何内容无关。再读一遍(仔细)并修复它。 RandomNum four(1000,9000)应该做什么?在什么上下文
  • 感谢您的意见这样更有意义吗?

标签: c++ class random numbers generator


【解决方案1】:

问题

你不能在表达式的中间声明一个变量,下面的都是错误的。

cout << RandomNum four(1000,9000); << endl;

cout << RandomNum three(100,900); << endl;

解决方案

更改main 的内容,首先将fourthree 声明为RandomNum 类型的实例并根据需要初始化它们,然后在cout 表达式.

RandomNum four (1000,9000); // declaration of `four`
RandomNum three (100, 900); // declaration of `three`

cout << four () << endl;

cout << three () << endl;

【讨论】:

  • 我现在明白了:)。要为每个创建 10 个,我包括 for 循环以迭代到 10。
  • 为了完整起见,您实际上可以创建“内联”对象,但通常不建议这样做,因为您的代码更难阅读,而且您正在创建和丢弃对象而不是可能重用它稍后(没那么糟糕,因为你的课在这里很轻):cout &lt;&lt; RandomNum(1000, 9000)() &lt;&lt; endl; 注意额外的括号和省略的实际名称。
猜你喜欢
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2020-11-29
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多