0

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;
}
user1884814
  • 31
  • 1
  • 1
  • 6

2 Answers2

4

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.

chris
  • 60,560
  • 13
  • 143
  • 205
  • @billz, Soon, yes. I noticed not long ago that I was close :) – chris Feb 12 '13 at 00:04
  • I changed the function to this| std::ostream& operator<<(std::ostream& out, Vector& v) { | But it made no difference, I still have the same error. – user1884814 Feb 12 '13 at 00:06
  • @user1884814, Change the second parameter to `const Vector &` because it isn't being modified, and make sure you change it in the declaration and definition. – chris Feb 12 '13 at 00:08
  • I've added the changes I made to the original post, still no difference. Let me know if you can see why it can't access the variables x, y, z in the header file if you can. – user1884814 Feb 12 '13 at 00:10
  • Please, I still need help. – user1884814 Feb 12 '13 at 00:28
  • What exactly are the errors you are getting? Please add the compiler error output to the question itself, that will definitely help. – Mats Petersson Feb 12 '13 at 00:34
1

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
Ryan Witmer
  • 331
  • 2
  • 8
  • Ah, I didn't notice the namespace. Easy enough to just wrap the cpp file in a `namespace vec {...}` – chris Feb 12 '13 at 00:39