c++ - Friend function can't access class variables -
i thought friend functions access class variables in how seek v.x, v.y, v.z in << function. doesn't compile. says it's unable resolve identifier @ lines.
also i'm trying larn how utilize namespaces. though utilize namespace vec in implementation file still have include vector:: before what's point?
header file:
#ifndef vector_h #define vector_h namespace vec { class vector { private: double x, y, z; public: vector(double, double, double); friend std::ostream& operator<<(std::ostream&, const vector&); }; } #endif /* vector_h */
.cpp file:
#include "vector.h" #include <iostream> using namespace vec; //constructor vector::vector(double x1 = 0, double y1 = 0, double z1 = 0) { x = x1; y = y1; z = z1; } //operators std::ostream& operator<<(std::ostream& out, const vector& v) { out<<"<"<<v.x<<", "<<v.y<<", "<<v.z<<">"; homecoming out; }
friend functions aren't fellow member functions, , operator<<
needs not fellow member in order have left side of ostream
. alter free function:
std::ostream& operator<<(std::ostream& out, vector v) { ^^ no qualification
i take vector const reference instead of value.
c++ namespaces friend
No comments:
Post a Comment