【问题标题】:How friend specifier does work in c++?朋友说明符如何在 C++ 中工作?
【发布时间】:2014-05-13 04:18:15
【问题描述】:

考虑以下代码:

#include <stdio.h>

class A
{
    friend void foo(){ printf("%d\n",_a); }
public:
    A(int);
private:
    static const int _a=5;
};

class B
{
    friend void foo(){ printf("%d\n",_a); }
private:
    static const int _a=6;
};

int main()
{
    foo();
}

编译后出现以下错误:

an_test.cpp:14:14: error: redefinition of ‘void foo()’
an_test.cpp:5:14: error: ‘void foo()’ previously defined here
an_test.cpp: In function ‘int main()’:
an_test.cpp:21:6: error: ‘foo’ was not declared in this scope
make: *** [an_test.o] Error 1

我认为用朋友说明符定义的函数是外部链接。那么为什么 an_test.cpp:21:6: error: ‘foo’ 没有在这个范围内声明呢?

【问题讨论】:

  • 首先:不要在类中定义它们。使用friend 根本没有意义。
  • 修复您的第一个错误redefinition of ‘void foo()’,然后重试。 foo 不在范围内,因为编译器未能创建它。
  • @πάνταῥεῖ,在类中定义它仍然有意义,但不是没有任何参数。
  • 内联好友功能只能使用ADL查找。

标签: c++ friend


【解决方案1】:

我发现了一些关于 C++ Friend 函数的内容,可以帮助您了解错误发生的原因:

C++ Friend Functions

注意:

一个类的友元函数是在该类的范围之外定义的,但是 它有权访问所有私有和受保护的成员 班级。即使友元函数的原型出现在 类定义,friends 不是成员函数。朋友可以是 函数、函数模板或成员函数,或类或类 模板,在这种情况下,整个类及其所有成员都是 朋友。

【讨论】:

    【解决方案2】:

    我认为您将 linkage 与范围界定混淆了。在您的代码中,两个foo() 定义的范围 都在它们各自的类中,因此main() 看不到它们的定义。

    如果您希望foo()main() 中可见,则需要将其声明移到外面,并在类内声明friend

    #include <stdio.h>
    
    class A
    {
        friend void foo(A a);
        public:
        A(int) {}
        private:
        static const int _a=5;
    };
    
    void foo(A a){ printf("%d\n",a._a); }
    
    int main()
    {
        foo(A(5));
    }
    

    如果定义在内部并且在外部有声明,则以下方法也可以使用。

    #include <stdio.h>
    
    class A
    {
    friend void foo(A a){ printf("%d\n",a._a); }
    public:
        A(int) {}
    private:
        static const int _a=5;
    };
    
     void foo(A a);
    
    
    int main()
    {
        foo(A(5));
    }
    

    【讨论】:

    • @Mankarse,我正要进行另一个测试。
    • 但是这句话“在朋友声明中首先声明的函数具有外部链接(3.5)。”呢??在我的情况下,所有函数都使用朋友声明声明,但它们在 main() 中不可见。
    • @DmitryFucintv,外部联动和内部联动的区别见this question。它与范围无关。
    【解决方案3】:

    我认为这个关于朋友范围的链接可以回答你的问题

    Friend scope in C++

    “Foo 是 A 的朋友”并不意味着“Foo”是“An_test”的朋友

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 2015-03-01
      • 1970-01-01
      • 2014-07-23
      • 2019-10-29
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多