0

我发现可以在类声明中定义朋友函数。我对它的含义有点困惑,因为类声明没有提供它的主体,一般来说它只是class A;.

友函数可以在类声明中定义(给定一个函数体)。这些函数是内联函数,就像成员内联函数一样,它们的行为就像是在看到所有类成员之后但在类范围关闭之前(类声明的结尾)立即定义的。在类声明中定义的友元函数在封闭类的范围内。

来源:https ://docs.microsoft.com/en-us/cpp/cpp/friend-cpp?view=vs-2019

4

2 回答 2

0

代表着

class A
{
public:
    friend std::ostream& operator << (std::ostream& os, const A&a)
    {
        return os << a.m1 << a.m2;
    }
};

相当于

class A
{
public:
    friend std::ostream& operator << (std::ostream& os, const A&a);
};

inline std::ostream& operator << (std::ostream& os, const A&a)
{
    return os << a.m1 << a.m2;
}
于 2020-04-23T20:58:00.533 回答
0

一个类声明可以同时是一个类定义。

您不能将友元函数定义放在未定义的类中。

考虑到如果没有在授予友谊的类之外声明这样的朋友函数,那么它是不可见的。它只能通过参数依赖名称查找来找到。

这是一个演示程序。

#include <iostream>

class A
{
private:
    int x;

public:
    A( int x ) : x ( x ) {}
    operator int() const { return x; }
    friend void f( const A &a )
    {
        std::cout << "a.x = " << a.x << '\n';
    }
};

void f( int x )
{
    std::cout << "x = " << x << '\n';
}

int main() 
{
    f( A( 10 ) );
    ( f )( A( 20 ) );

    return 0;
}

程序输出为

a.x = 10
x = 20

在这次通话中

f( A( 10 ) );

由于参数相关查找,找到了友元函数的名称。

在这次通话中

( f )( A( 20 ) );

将函数名括在括号中会关闭参数依赖查找并调用非友元函数。

或者你可以使用一个合格的函数名,比如

::f( A( 20 ) );

在这种情况下,ADL 也将不起作用,并且将调用非朋友函数。

还要记住,类中定义的友元函数在类的词法范围内。这意味着它可以使用类成员的名称。在类外定义的友元函数不在类的词法范围内。

于 2020-04-23T20:59:01.393 回答