user1884814
user1884814

Reputation: 31

Friend function can't access class variables

I thought that friend functions could access class variables as in how I try to do v.x, v.y, v.z in the << function. But it doesn't compile. It says it's unable to resolve identifier at those lines.

Also I'm trying to learn how to use namespaces. Even though I use the namespace vec in the implementation file I still have to include Vector:: before everything so what's the 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<<">";
    return out;
}

Upvotes: 0

Views: 870

Answers (2)

Ryan Witmer
Ryan Witmer

Reputation: 331

Your friend function belongs to the namespace vec and must be defined as such.

Change it to:

std::ostream &vec::operator << (std::ostream &out , const Vector &v) { //etc

Upvotes: 1

Qaz
Qaz

Reputation: 61900

Friend functions aren't member functions, and operator<< needs to not be a member in order to have a left side of ostream. Change it to a free function:

std::ostream& operator<<(std::ostream& out, Vector v) {
              ^^ no qualification

I would also take the vector by const reference instead of by value.

Upvotes: 4

Related Questions