Reputation: 861
I have a class that saves a student data. Before it will be stored, the ID will be check first if valid or not. In overloading the operator >>, I call the validate_id function. I already declared it as a friend, however upon compiling, it says 'validate_id was not declared in scope
. Is it because its a static function?
#include <iostream>
#include <string>
#include <locale>
#include <utility>
#include <algorithm>
#include <stdexcept>
typedef std::pair<std::string, std::string> Name;
class Student {
public:
Student(){};
bool operator <( const Student& rhs ) const {
return ( id_ < rhs.id_ );
}
friend std::ostream& operator <<(std::ostream& os, const Student& s);
friend std::istream& operator >>(std::istream& is, Student& s);
private:
std::string id_;
Name name_;
static bool validate_id(const std::string& id){
if(id.length() != 9 && id[0] != 'a')
return false;
for(size_t i = 1, sz = id.length(); i < sz; i++){
if(!isdigit(id[i]))
return false;
}
return true;
}
};
std::ostream& operator <<(std::ostream& os, const Student& s){
return os << s.id_ << " " << s.name_.first << " " << s.name_.second;
}
std::istream& operator >>(std::istream& is, Student& s){
is >> s.id_ >> s.name_.first >> s.name_.second;
if(!validate_id(s.id_)) // error here, says validate_id is not in scope
throw std::invalid_argument( "invalid ID" );
return is;
}
Upvotes: 0
Views: 4022
Reputation: 169
When you are calling a static member function in c++, you have to call it with the class scope. that means here you have to use
!Student::validate_id(s_id)
Meaning of a Static is that what ever you declared is goes to class scope.Not to object scope. That's why you have to call it with the class.
Upvotes: 0
Reputation: 32
Either declare validate_id
outside of the Student
class or call Student.validate_id
.
Upvotes: -1
Reputation: 227370
validate_id
is a static member of Student
, so you need to use the class' scope to name it:
if(!Student::validate_id(s.id_))
^^^^^^^^^
Upvotes: 2