跨多个文件的友元功能
Friend function across multiple files
你好,我正在学习运算符重载和友元函数。
我已经在 .h 文件中将运算符<<函数声明为我的类的朋友,但我仍然无法从.cpp文件中的函数定义访问私有成员变量
我的代码如下:
测试.h
class Test
{
private:
int size;
public:
friend ostream& operator<< (ostream &out, Test& test);
};
测试.cpp
#include "Test.h"
#include <iostream>
using namespace std;
ostream& operator<< (ostream& out, Test& test)
{
out << test.size; //member size is inaccessible!
}
显然大小是无法访问的,尽管我已经将运算符<<函数作为我类的朋友。我已经谷歌了一下,没有找到任何东西,所以有人可以帮助我吗?谢谢。
注意:如果我将类定义移动到.cpp文件中,每个人都可以工作,因此我认为我的问题与多个文件有关。
在 c++ 中,声明的范围从上到下。因此,如果您包括第一个Test.h
,然后<iostream>
朋友声明不知道类型std::ostream
。
解决方案:
测试.h:
#include <iostream>
class Test
{
private:
int size;
public:
friend std::ostream& operator<< (std::ostream &out,const Test& test);
};
测试.cpp:
#include "Test.h"
std::ostream& operator<< (std::ostream& out,const Test& test)
{
out << test.size;
return (*out);
}
请注意,#include <iostream>
已从Test.cpp
移至Test.h
,全局operator <<
的参数需要常量Test& test
。常量使运算符适用于右值。
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 如何启用友元类的友元功能直接在C++中访问其私有成员
- 模板类的友元功能
- 具有自动和友元功能的返回类型匹配
- C++ <<运算符重载,无友元功能
- 一个非成员函数如何实现一个类的友元函数的功能
- 前向声明和友元功能
- 跨多个文件的友元功能