#include <iostream>
#include<cstdlib>
#include<ctime>
usingnamespace std;
class Event{
private:
int number;
public:
int Random();
};
int Event::Random(){
int number = 0;
srand(time(0));
number = (rand() % 100 + 1);
return number;
};
int main(){
cout << "Hello world" << endl;
for(int i=0;i > 30; i++)
{
cout << Event.Random();
//There error is here, it says nonstatic member reference must be relaive to a specific object
}
system("pause");
return 0;
}
Hi, Im just trying to get this to return a random number. And I know the problem, just dont know how to fix it.
Hello, Calebob.
First of all, you've already declared the "number" field in the class, so remove the int number = 0 line from your Random() function. This function already has access to that field . You should make a constructor for the Event class. Write after public: the following code : Event() { number = 0;}
This way you'll be sure that number is set to 0 once an object of that class is created.
You should read about set methods and constructors to find out what is the correct way to give values to fields.
Then, you should take some time and read about what IS a class and what IS an object , so that you'll understand that in order to use the class you've created ,you must declare an object of type Event in your main function ,lets call it event1. You write Event event1;. You now have an object of type Event and you can use event1.Random() to call the function. Edit cout << Event.Random(); to cout << event1.Random();.
In your for loop , you should change i>30 to i<30 ,.Starting i with 0 will run Event.Random() exactly 0 times,since 0 is not greater than 30, so you will get no output. With for(int i=0; i<30; i++) you will get 30 calls of event1.Random();
And that's all, the program should output now 30 random numbers.
This was my first experience for forums so, I sorta forgot some things that other people need to know ha. But to Pva, thank you. I've just gettin back into the swing of programming an obviously I'm very rusty.
Now its outputting numbers in sequence, not in random. starting from zero, and running with the program clock its givin me sequencial numbers i.e 13, (press enter) 16, 19, 21, 31 (longer pause between enter).
This forum has rules.One of them is to use code tags when inserting some code. Write "code" between [] before the code and "/code" between [] at the end of the code.