Primes Class
Apr 6, 2011 at 11:37pm UTC
I can't seem to get my friend function to work. I looked at the tutorial and I think I got the syntax correct, but I'm getting this compiler error:
59 `plist' undeclared (first use this function)
Doesn't the function have access to private members?
Here's the header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#ifndef __PRIMES_HPP
#define __PRIMES_HPP
#include <vector>
#include <string>
class primes
{
public :
//constructors
primes(int );
primes(char *, int );
primes(std::string, int );
//public member functions
friend bool ptest(uint64_t);//
int operator [] (int );
int at(int );
int size();
int back();
private :
std::vector <int > plist;
};
#endif
And the implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#include "primes.hpp"
#include <fstream>
#include <vector>
#include <cmath>
#include<iostream>
primes::primes(int size)
{
std::vector <bool > sieve(size);
for (int i = 2; i < size; i++)
if (!sieve[i])
{
plist.push_back(i);
for (int j = 1; i*j < size; j++)
sieve[i*j] = 1;
}
}
primes::primes(char *filename, int size)
{
std::ifstream in(filename);
if (!in)
{
std::cout << "Error opening file.\nFile \'" << filename << "\' may not exist.\n" ;
std::cin.get();
}
int temp;
in >> temp;
while (temp < size)
{
plist.push_back(temp);
in >> temp;
}
}
primes::primes(std::string filename, int size)
{
primes(filename.c_str(), size);
}
int primes::operator [] (int index)
{
return plist[index];
}
int primes::at(int index)
{
return plist.at(index);
}
int primes::back()
{
return plist.back();
}
bool ptest(uint64_t number)//this function was declared friend
{
for (int i = 0; plist[i] <= sqrt(number); i++)//is sqrt() bad?
if (number%plist[i] == 0)
return false ;
return true ;
}
Last edited on Apr 6, 2011 at 11:40pm UTC
Apr 7, 2011 at 12:34am UTC
it should be bool primes::ptest(uint64_t number)
and there is no need for friend. ptest() is just another member function, just like at() or back().
Apr 7, 2011 at 12:36am UTC
Friend functions don't have normal scope rules for accessing the class. You need to have the Class represented in the function's arguments and access it through there...
for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// the friend function.
CString operator +(char *pString, CString &cStr)
// ^working variable...
// ^the class reference.
{
// CString =
int nLen = strlen(pString)+strlen(cStr.c_str()) +1;
CString strTmp;
delete [] strTmp.m_pString;
strTmp.m_pString = new char [nLen];
strcpy(strTmp.m_pString, pString);
strcpy(strTmp.m_pString, cStr.c_str());
return strTmp;
// friend function...
}
Last edited on Apr 7, 2011 at 12:36am UTC
Topic archived. No new replies allowed.