cannot access private members in friend ostream(无法访问朋友 ostream 中的私人成员)
问题描述
我试着交朋友 ostream
功能.编译器说我不能访问该类的私有成员,即使我将它声明为 friend
.我读了一个类似的问题,它说问题出在namespcaes上.(问题: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 中的私人成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法访问朋友 ostream 中的私人成员
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01