0

由于可以在本地类中声明友元函数,如下例所示。如果在函数定义中定义了本地类的成员,而在它之外无法访问,那么它如何用于访问本地类的成员?

void foo()
{
    void bar();

    class MyClass
    {
        int x;
        friend void bar();
    };
}

void bar() { // error: cannot access local class here }

int main()
{
    //..
}
4

3 回答 3

1

本地类中的friend函数声明对于函数模板特化仍然有用。这仅在 C++11 中是正确的,因为在 C++03 中,本地类型不能是模板参数。

template< typename t >
int bar( t &o ) {
    return ++ o.x;
}

int main()
{
    class MyClass
    {
        int x;

        friend int bar<>( MyClass &o );

    public:
        MyClass() : x( 0 ) {}
    };

    MyClass m;

    std::cout << bar( m ) << ", " << bar( m ) << '\n';
}

http://ideone.com/vcuml

否则,我看不出这样的声明如何完成任何事情。

于 2012-01-05T08:03:34.597 回答
1

MyClass 在 foo() 之外无法访问,因此您无法从 foo() 外部访问它的任何方法。

如果您想在对 foo() 的调用完成后使用 bar(),请让 MyClass 从某个基类继承或实现某个接口,然后您就可以调用其实现该接口的方法。

于 2012-01-05T06:50:28.647 回答
1

函数bar()无法访问函数中class MyClass定义的内容foo()。如果您需要访问该类,请将其从foo()函数中取出。

于 2012-01-05T06:50:38.720 回答