gpt4 book ai didi

c++ - 为什么 PRIVATE 成员函数不能成为另一个类的友元函数?

转载 作者:IT老高 更新时间:2023-10-28 21:56:23 26 4
gpt4 key购买 nike

class x
{
void xx() {}
};

class y
{
friend void x::xx();
};

这会导致类似

的错误

error: friend function 'xx' is a private member of 'x'

为什么我不能将私有(private)成员函数声明为另一个类的 friend ?

最佳答案

[class.friend]/9 :

A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration.

原因很简单; private 成员必须遵守明确的规则:

A member of a class can be

  • private; that is, its name can be used only by members and friends of the class in which it is declared.

允许在不相关类的声明中命名私有(private)成员将违反此规则:它允许另一个类依赖于实现细节而无需明确允许。例如,当更改私有(private)成员的名称、类型或签名,或将其完全删除时,这会成为问题;这是为了不破坏该类的接口(interface)。

这可以通过使整个x成为y的 friend 来规避:

class x {
void xx() {}
};

class y {
friend x;
};

Demo .

关于c++ - 为什么 PRIVATE 成员函数不能成为另一个类的友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26956176/

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