Learning c++ bit by bit in codeblocks, I encountered this error. I have tried it for hours and saw various links but its still not working,
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
foo:: Person p;
//std:: cin >> p;
std:: cout << p;
return 0;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
namespace foo{
class Person
{
public:
int age;
Person();
friend std:: ostream& operator << (std::ostream&,const Person&);
//friend std:: istream& operator << (std:: istream& in, Person& p);
protected:
private:
// std::string name;
};
}
#endif // PERSON_H
Person.cpp
#include <iostream>
#include "Person.h"
using namespace foo;
Person::Person()
{
age = 0;
//name = "noname";
}
std:: ostream& operator <<(std:: ostream& out, Person const &p)
{
out << "Extraction operator" << std:: endl << p.age << std:: endl;
// out << p.name << std::endl;
return out;
}
/*std:: istream& operator >>(std:: istream& in, Person &p)
{
in >> p.age >> p.name;
return in;
}*/
Q1. Why do we need to create the header file and Person.cpp in a seperate namespace? Guess: Is it because cout would simply mean the global namespace and then we again have a overloaded cout so which definition is the compiler going to call its not sure?
Q2. By creating a object p of Person class in foo namespace in main and calling std:: cout << p, what are we trying to do? (std is in std namespace and we want to call the overloaded operator)
Error:
undefined reference to foo:: operator<<(std::ostream&, foo::Person const&)')
If we write the age in private it says that its is private but being a friend it should have access to private members. I know it's something related to namespace but I can't find out the reason.
no match for operator >> in std::cin Earlier it was giving the above and many other error so I tried using two namespaces but still its not working.