Can you please me give an example of a class called \"prime\" that overloads its
ID: 3585838 • Letter: C
Question
Can you please me give an example of a class called "prime" that overloads its function operator to act as a function object. Instantiate a "prime" object in the main program and use it to test the input data.
Class prime would just check if integers stored from the user in a vector is a prime number or not in a loop until user breaks loops with CTRl D.
I am confused about the overloading part..
Can you please add comments anywhere and everywhere so it can be very easy to read and understand code?
Explanation / Answer
#include<iostream>
#include<math.h>
#include<vector>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
class prime {
public :
virtual bool operator() (int a){
for(int i = 2; i<=sqrt(a); i++){
if (a % i == 0)
return false;
}
return true;
}
};
bool isPrime(int a, prime *func){
return (*func)(a);
}
int main(){
vector<int> data;
char line[10];
int a = 5;
prime* p1 = new prime(); // This object p1 we are using it as function object for the operator function defined in the class prime.
while (1){
if (fgets(line,10,stdin) == NULL)
break;
a = atoi(line);
data.push_back(a);
if (isPrime(a,p1))
cout << "It is a prime" << endl;
else
cout << "It is not a prime" << endl;
}
return 0;
}