gpt4 book ai didi

c++ - friend 说明符如何在 C++ 中工作?

转载 作者:行者123 更新时间:2023-11-30 04:04:45 26 4
gpt4 key购买 nike

考虑以下代码:

#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' was not declared in this scope?

最佳答案

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

C++ Friend Functions

注意:

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

关于c++ - friend 说明符如何在 C++ 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com