Search code examples
c++classfriend-function

Friend function haven't got access to private members


Just now I'm started to writing in OOP C++. I want to include arithmetical operations in my class which represent 2D vector in physics.

Ok. End offtop I have a problem with access to private member form friend function. I write friend declaration in class block, but I still haven't got access to vector's private members and i don't know why.

Did I do not understand this?

This is a code:

vector2d.h:

    /* NAMESPACE */
 #define _NEDLIB_BEGIN namespace nedlib {
 #define _NEDLIB_END }

_NEDLIB_BEGIN
    #define COORD double // set type of coordinates

class vector2d
{
private:
    COORD x, y;

public:
        /* CONSTRUCTORS */
    // [...] - if it's important, i will show full class code

        /* DESTRUCTORS */
    ~vector2d();

        /* MEMBER FUNCTIONS*/
    // [...] - if it's important, i will show full class code


        /* Friend functions */
    friend vector2d operator *(const double & real, const vector2d & vector); // problem
    friend ostream & operator <<(ostream & screen, const vector2d & vector); // problem

}; /* class vector2d */


// ********************************************************************************
    /* operators */

    // vector2d operator *(const double & real, const vector2d & vector);
    // ostream & operator <<(ostream & screen, const vector2d & vector);

double RadToDeg(double);
double DegToRad(double);

_NEDLIB_END

vector2d.cpp

 using namespace nedlib;

    vector2d operator *(const double & real, const vector2d & vector)
    {
        return vector2d(vector.x * real, vector.y * real); // problem
    }

    ostream & operator <<(ostream & screen, const vector2d & vector)
    {
        screen << "(" << vector.x << ", " << vector.y << ")"; // problem
        return screen;
    }

double RadToDeg(double rad)
{
    return (180.0 * rad / M_PI);
}

double DegToRad(double deg)
{
    return (deg * M_PI / 180.0);
}

Visual error: (four errors, but all almost the same)

Severity Code Description Project File Line Error (active) member "nedlib::vector2d::x" (declared at line 21 of "c:\Users\Nedziu\Documents\Visual Studio 2015\Projects\Ned Library\Ned Library\vector2d.h") is inaccessible Ned Library c:\Users\Nedziu\Documents\Visual Studio 2015\Projects\Ned Library\Ned Library\vector2d.cpp 208


Solution

  • You have declared your operator functions inside the nedlib namespace

        vector2d operator *(const double & real, const vector2d & vector);
        ostream & operator <<(ostream & screen, const vector2d & vector);
    
    _NEDLIB_END // <<<<<<
    

    Thus you have to qualify the namespace in the function definition:

    vector2d nedlib::operator *(const double & real, const vector2d & vector);
          // ^^^^^^^^
    

    using namespace nedlib;
    

    doesn't affect the scope of definitions seen within the translation units where it is used.