跨多个文件的友元功能

Friend function across multiple files

本文关键字:友元 功能 文件      更新时间:2023-10-16

你好,我正在学习运算符重载和友元函数。

我已经在 .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。常量使运算符适用于右值。