c++ - Operator<< cant access private int of class -


i when try compile:

../monster.h:26:9: error: ‘int projectiv::monster::con’ private

`int con;`      ^ 

../monster.cpp:17:39: error: within context

cout << "constitution: " << monster.con << endl; ^

make: * [monster.o] error 1

from understand making operator<< friend should allow access int con. not seeing.

monster.h:

#ifndef monster_h_ #define monster_h_  #include <iostream> using std::cout; using std::endl; using std::ostream; #include <string> using std::string;  namespace projectiv {   class monster   {   friend ostream &operator<< (ostream &out, const monster &monster);   public:     monster(int con);   private:     int con;   }; } /* namespace projectiv */  #endif /* monster_h_ */ 

monster.cpp:

#include "monster.h"  ostream &operator<< (ostream &out, const projectiv::monster &monster) {   cout << "constitution: " << monster.con << endl;    return out; }  projectiv::monster::monster(int con): con(con) {} 

main.cpp:

#include "monster.h" using namespace projectiv;  int main() {   monster gojira(140);   cout << gojira << endl;   return 0; } 

this:

ostream& operator<<(ostream& out, const projectiv::monster& monster) 

should be:

ostream& projectiv::operator<<(ostream& out, const projectiv::monster& monster) 

here not working example, , here working one.


also, per andreyt's comment, should add function declaration before friend declaration:

namespace projectiv {     class monster {     friend ostream& operator<<(ostream& out, const monster& monster);     public:         monster(int con);     private:         int con;     };     ostream& operator<<(ostream& out, const monster& monster);     // ^^^ } 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -