test
RandomNumberGenerator rng;
cout << rng() << endl;
header
class RandomNumberGenerator {
public:
unsigned long operator()();
};
cpp
unsigned long operator()() { // HERE IS ERROR
srand(time(NULL));
unsigned long r = rand();
return r;
}
basically im trying to do a random number generator. but getting an error :
开发者_如何学PythonC:\CodeBlocks\kool\praks3\src\myfunctors.cpp|5|error: 'long unsigned int operator()()' must be a nonstatic member function|
You need to tell the compiler that the operator()()
belongs in the RandomNumberGenerator
class by using ::
:
unsigned long RandomNumberGenerator::operator()()
{
srand(time(NULL));
unsigned long r = rand();
return r;
}
The compiler says that it "must be a nonstatic member function" because operator()()
is required to be a member of a class and not a global function. And without the scoping operator the compiler thinks that the operator()()
is a global function and thus not a member of RandomNumberGenerator
, which is the source of the error.
Don't forget to include the header for the RandomNumberGenerator
class into the source file!
Outside the class, this is how you've to define the operator()
:
unsigned long RandomNumberGenerator::operator()() {
//note this ^^^^^^^^^^^^^^^^^^^^^^^
srand(time(NULL));
unsigned long r = rand();
return r;
}
The part RandomNumberGenerator::
tells the compiler that operator()
belongs to the class RandomNumberGenerator
.
You are not scoping your operator.
Try this:
unsigned long RandomNumberGenerator::operator()() {
srand(time(NULL));
unsigned long r = rand();
return r;
}
Regards,
Dennis M.
You forgot to specify the scope, try unsigned long RandomNumberGenerator :: operator()()
The point is, how should the compiler otherwise know to which class your operator()
belongs to?
精彩评论