M
M
Milton8122017-05-31 19:56:40
OOP
Milton812, 2017-05-31 19:56:40

How to create a method so that it sets random properties to an object?

There is a program that has a class that has a method that should set random parameters to an object of the class, but when this method is applied to two different objects of the class, the result is the same. How can I modify the program so that each time this method is applied to an object, a different result is obtained?

spoiler
#include <iostream>
#include <ctime>

using namespace std;

enum Level {easy=1, hard, medium};

class alpha
{
private:
  Level level;
  int number;
public:
  alpha() : level(easy), number(5)
  {}

  void gen()
  {
    srand(time(NULL));
    number = rand() % 10 + 1;
    int levelgen = rand() % 3 + 1;
    switch (levelgen)
    {
    case 1:
      level = easy;
      break;
    case 2:
      level = medium;
    case 3:
      level = hard;
    default:
      break;
    }
  }
  void disp()
  {
    if (level == hard)
      cout << "level - ???? " << endl;
    else
    {
      cout << "level = ";
      switch (level)
      {
      case easy:
        cout << "easy" << endl;
        break;
      case medium:
        cout << "medium" << endl;
        break;
      default:
        break;
      }
    }
    cout << "number = " << number << endl;
  }
};

int main()
{
  srand(time(NULL));
  alpha obj1;
  obj1.gen();
  obj1.disp();
  alpha obj2;
  obj2.gen();
  obj1.disp();
  system("pause");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devalone, 2017-05-31
@milton812

srand(time(NULL));
Should be at the beginning of the program, although it is better to use a normal PRNG. And the problem is that you are displaying the data of the same object:

alpha obj1;
  obj1.gen();
  obj1.disp();
  alpha obj2;
  obj2.gen();
  obj1.disp();

Take a closer look at the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question