朋友功能无法访问私有成员

Friend function haven't got access to private members

我刚刚开始用 OOP C++ 编写代码。我想在我的 class 中包含算术运算,它代表物理学中的二维向量。

好的。结束 offtop 我在访问私人成员形式的朋友功能时遇到问题。 我在 class 块中写了 friend 声明,但我仍然无法访问 vector 的私有成员,我不知道为什么。

我是不是没看懂?

这是一个代码:

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);
}

视觉错误:(四个错误,但都差不多)

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

您已在 nedlib 命名空间

中声明了您的运算符函数
    vector2d operator *(const double & real, const vector2d & vector);
    ostream & operator <<(ostream & screen, const vector2d & vector);

_NEDLIB_END // <<<<<<

因此您必须在函数定义中限定命名空间:

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

using namespace nedlib;

不影响在使用它的翻译单元中看到的定义范围。