提问者:小点点

用于输出流运算符的友元函数显示错误为不可访问


我在vrkvector.h文件中编写了如下所示的简单类。

namespace vrk {
class VRKVector {

private:
    std::vector<int> m_coordinates;
    int              m_dimension;


public:
    /** VRKVector constructor.
      * @param coordinates wich represents a vector coordinates.
      * @return none.
    */
    VRKVector(std::vector<int> coordinates);

    /** operator << : output stream operator
      * @param out which is output stream we want to write
      * @param vector wich represents a vector coordinates.
      * @return none.
    */
    friend std::ostream& operator << (std::ostream& out, vrk::VRKVector& vrkvector);

    };
}

VRKVector.cpp

// ============================================================================
// Local includes, e.g. files in the same folder, typically corresponding declarations.
#include "VRKVector.h"


// ============================================================================
// System includes, e.g. STL.
#include <iostream>
#include <fstream>
#include <sstream> 
#include <iterator>
#include <algorithm>




// namespace declarations;
using namespace std;
using namespace vrk;

VRKVector::VRKVector(std::vector<int> coordinates) {
    m_coordinates = coordinates;
    m_dimension = coordinates.size();
}


std::ostream& operator<< (std::ostream& out, vrk::VRKVector& vrkvector) {
    out << vrkvector.m_dimension;
    return out; // return std::ostream so we can chain calls to operator<<
}

上面的代码我得到了如下所示的错误

1>C:\VRKVector.cpp(42,18): error C2248: 'vrk::VRKVector::m_dimension': cannot access private member declared in class 'vrk::VRKVector'
1>C:\\VRKVector.h(40): message : see declaration of 'vrk::VRKVector::m_dimension'

我们可以评估私人成员,因为我们有朋友功能。 为什么我看到了错误。

谢谢


共2个答案

匿名用户

您需要在命名空间vrk中定义运算符<<<friend声明将其声明为命名空间vrk的成员。

在类或类模板X内的友元声明中首次声明的名称将成为X的最内部封闭命名空间的成员,。。。

std::ostream& vrk::operator<< (std::ostream& out, vrk::VRKVector& vrkvector) {
//            ^^^^^
    out << vrkvector.m_dimension;
    return out; // return std::ostream so we can chain calls to operator<<
}

匿名用户

std::ostream& operator<< (std::ostream& out, vrk::VRKVector& vrkvector){} 

不是的定义

friend std::ostream &operator<<(std::ostream &out, vrk::VRKVector &vrkvector);

由于它位于不同的命名空间中,因此它无法访问类私有成员,这是试图访问给定类私有成员的全局函数所期望的。

您可以通过以下方法修复:

  • 内联定义它:
friend std::ostream &operator<<(std::ostream &out, vrk::VRKVector &vrkvector){
    out << vrkvector.m_dimension;
    return out; // return std::ostream so we can chain calls to operator<<
}

>

  • 在命名空间内定义它。

    使用命名空间范围:

    std::ostream& vrk::operator<< (std::ostream& out, vrk::VRKVector& vrkvector) { 
        /*...*/
    }