成员无法使用好友功能访问
Members inaccessible with friend function
我收到一个无法解释的错误。这是我的头文件:
#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
friend ostream& operator<<(ostream& out, const Matrix& object);
friend istream& operator>>(istream& in, Matrix& theArray);
//Default Constructor
Matrix();
Matrix(int max_number_rows, int max_number_cols, int intial_value);
//Destructor
~Matrix();
//Copy Constructor
Matrix(const Matrix& right_side);
//Assignment Operator
Matrix& operator=(const Matrix& right_side);
void Clear();
int Rows();
int Columns();
bool GetCell(int x,int y, int& val);
bool SetCell(int x,int y, int val);
//void Debug(ostream& out);
private:
int initialVal;
int rows;
int cols;
IntArrayPtr *m;
};
#endif
}
这是我的定义:
ostream& operator<<(ostream& out, const Matrix& object)
{
for(int r = 0; r < object.rows; r++)
{
for(int c = 0; c < object.cols; c++)
{
out << object.m[r][c] << " ";
}
out << endl;
}
return out;
}
它给了我一个错误,即 Matrix.h 成员无法访问,但我明确指出它们是好友功能。
这些函数定义位于何处?friend
声明将名称注入namespace project
。如果函数未在该命名空间中定义,则它们是不同的函数,而不是友元。
您的函数实现也应该驻留在 project
命名空间中 - 仅仅声明您正在使用它是不够的,如果您不这样指定它,函数本身就是"全局",然后无法访问成员,因为它在错误的命名空间范围内是好友。
使用此修复程序可以正常编译。
否则不编译。
尝试在 Matrix 类之外定义两个友元函数。
喜欢:
#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
//Default Constructor
Matrix();
Matrix(int max_number_rows, int max_number_cols, int intial_value);
//Destructor
~Matrix();
//Copy Constructor
Matrix(const Matrix& right_side);
//Assignment Operator
Matrix& operator=(const Matrix& right_side);
void Clear();
int Rows();
int Columns();
bool GetCell(int x,int y, int& val);
bool SetCell(int x,int y, int val);
//void Debug(ostream& out);
private:
int initialVal;
int rows;
int cols;
IntArrayPtr *m;
};
ostream& operator<<(ostream& out, const Matrix& object);
istream& operator>>(istream& in, Matrix& theArray);
#endif
}
相关文章:
- 有没有可能有一个只有ADL才能找到的非好友功能
- 解析模板的好友功能时出现问题
- 特定好友功能专业化
- 好友功能 - 成员无法访问
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- 好友功能仍无法访问私人会员
- CUDA C++中的好友功能
- 好友功能没有访问私人成员
- 我无法正确使用好友功能
- 如何更恰当地处理好友功能
- 为什么我的好友功能无法访问私人会员?
- 好友功能和受保护的数据
- 选择何时使用好友功能
- 好友功能"non-lvalue in assignment"
- 好友功能无法访问私人数据成员
- 在C++中使用好友功能有什么额外的优势?
- 成员无法使用好友功能访问
- 好友功能 - 无法访问私人字段C++
- 关于C++中的好友功能
- 访问好友功能