无法访问朋友ostream中的私人成员 [英] cannot access private members in friend ostream

查看:92
本文介绍了无法访问朋友ostream中的私人成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图结交朋友ostream功能.编译器说,即使我将其声明为friend,也无法访问该类的私有成员.我读了一个类似的问题,它说问题出在名称pcaes.(问题是: C ++朋友功能无法访问私有成员)

I tried to make friend ostream function. The compiler say i cannot access private member of the class, even though i declared it as friend. I read a similar question and it say the problem is with the namespcaes.(the question: C++ friend function can't access private members)

我的代码如下:

标题:

#include <iostream>
#include <string>
//using namespace std;

namespace biumath
{
#ifndef BIUMATH_H
#define BIUMATH_H
class Assignment
{
private:
    int **m_varArray;
    int m_rowsOfVarArray;
public:
     Assignment(); //1
     Assignment(char symbol, double value); //2
     bool containsValueFor(char symbol) const; //3
     double valueOf(char symbol) const; //4
     void add(char symbol, double val); //5
     friend std::ostream& operator<< (std::ostream& out, 
     const Assignment& assignment);
};
}
#endif

cpp:

#include <iostream>
#include "biumath.h"
using namespace biumath;
using std::cout;
using std::endl;

ostream& operator<< (ostream& out, 
     const Assignment& assignment){
        out<<assignment.m_rowsOfVarArray<<std::endl;
        //return the stream. cout print the stream result.
        return out;
}

推荐答案

或者更好的是,通过遵循公共实用程序方法来避免所有不必要的友谊(当您的Assignment是多态基类时,这也会有所帮助):

or better yet, avoid all unnecessary friendships by deferring to a public utility method (this also has benefits when your Assignment is a polymorphic base class):

在头文件中:

namespace biumath
{
    class Assignment
    {
    private:
        int **m_varArray;
        int m_rowsOfVarArray;
    public:
        Assignment(); //1
        Assignment(char symbol, double value); //2
        bool containsValueFor(char symbol) const; //3
        double valueOf(char symbol) const; //4
        void add(char symbol, double val); //5
        void write(std::ostream& os) const; // <=== public helper
    };

    // free function overload which defers to helper.
    // NOTE: it's in the biumath namespace so ADL will find it

    inline std::ostream& operator<< (std::ostream& out,
                                       const Assignment& assignment){
        assignment.write(out);
        return out;
    }
}

在CPP文件中:

namespace biumath {

    void Assignment::write(std::ostream& os) const {
        os << m_rowsOfVarArray << std::endl;
    }
}

这篇关于无法访问朋友ostream中的私人成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆