【问题标题】:Friend function across multiple files跨多个文件的好友功能
【发布时间】:2014-05-16 14:39:07
【问题描述】:

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

我已在 .h 文件中将 operator

我的代码如下:

测试.h

class Test
{
private:
    int size;
public:
    friend ostream& operator<< (ostream &out, Test& test);
};

Test.cpp

#include "Test.h"
#include <iostream>

using namespace std;

ostream& operator<< (ostream& out, Test& test)
{
    out << test.size; //member size is inaccessible!
}

虽然我已经让 operator

注意:如果我将类定义移动到 .cpp 文件中,每个人都可以工作,所以我认为我的问题与多个文件有关。

【问题讨论】:

    标签: c++ function overloading operator-keyword friend


    【解决方案1】:

    在 C++ 中,声明的范围是从上到下的。因此,如果您首先包含Test.h,然后包含&lt;iostream&gt;,则朋友声明不知道std::ostream 的类型。

    解决办法:

    测试.h:

    #include <iostream>
    class Test
    {
    private:
        int size;
    public:
        friend std::ostream& operator<< (std::ostream &out,const Test& test);
    };
    

    Test.cpp:

    #include "Test.h"
    
    std::ostream& operator<< (std::ostream& out,const Test& test)
    {
        out << test.size;
        return (*out);
    }
    

    请注意,#include &lt;iostream&gt; 已从 Test.cpp 移动到 Test.h,并且全局 operator &lt;&lt; 的参数采用 const Test&amp; test。 const 使运算符为rvalues 工作。

    【讨论】:

    • 标题中的#include &lt;iosfwd&gt; 和cpp 文件中的#include &lt;iostream&gt; 应该足够了。
    猜你喜欢
    • 2021-10-25
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2011-03-27
    • 2015-08-02
    • 2012-02-09
    • 1970-01-01
    相关资源
    最近更新 更多