I am trying to create a class for doing number factorization on a random number, so I need to create a pointer to store the factors of the number. But when I compiled it, I got an error. My question is 1)What did I do wrong? I have a feeling I did something wrong with the initialization, but I just couldn't pinpoint what the problem is. 2) Is there a better way to store a set of numbers beside using member pointer? for example, a member array. :)
Output:
1
2
3
t.cpp: In constructor 'numFactor::numFactor(int, int*)':
Line 14: error: expected identifier before '*' token
compilation terminated due to -Wfatal-errors.
#include <iostream>
#include <ctime>
using namespace std;
class numFactor{
protected:
int *factorPtr;
int factorSize;
int inputNum;
public:
//Constructor
numFactor(int num=0, int *ptr=NULL)
:inputNum(num),*factorPtr(&ptr)
{}
//Mutator
void setinputNum(){inputNum=2+rand()%98;}
void setfactorPtr();
//Accessor
int getinputNum(){return inputNum;}
int* getfactorPtr(){return factorPtr;}
int getfactorSize(){return factorSize;}
//Display
void printinputNum();
void printfactorPtr();
};
void numFactor::setfactorPtr()
{
// Find factors and put it in a stack
stack<int> factorStack;
for(int i = 2; i < number; i++) // Test for factors > 1
{
if(number % i == 0) // It is a factor > 1
{
bool factor = true;
if(factor)
factorStack.push(i);
}
}
//store the size of the factor
factorSize=(int) factorStack.size();
// Store the stack in a pointer;
*factorPtr=new int[factorSize];
for(int i=0;i<factorSize;i++)
{ *(factorPtr+i)=factorStack.top();
factorStack.pop();
}
}
void numFactor::printinputNum()
{ cout<<"The input number is "<<inputNum<<endl;
}
void numFactor::printfactorPtr()
{ cout<<"The factor(s) is/are "
for(int i=0; i<factorSize;i++)
{ cout<<*(factorPtr+i)<<" ";}
cout<<endl;
}
int main()
{ srand((unsigned) time(0));
numFactor test;
test.setinputNum();
test.setfactorPtr();
test.printinputNum();
test.printfactorPtr();
return 0;
}