访问说明符对朋友功能重要吗?
Does access specifier matters for a friend function?
在一个类中,如果函数在不同的说明符(如 private、protected 或 public)中声明为 friend,那么有什么区别。据我了解,朋友功能不是成员。因此,这应该无关紧要。但是,如果我看到 static - 它也不是成员,但访问说明符很重要。所以,我有点困惑。所有这些代码如何正常工作?下面的类有区别吗?
/** Private friend function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
};
/** Protected -- Friend Function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
protected:
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
不,没关系。
C++ 标准,第 11.3 / 9 节 [friend.class]
The meaning of the friend declaration is the same whether the friend
declaration appears in the private, protected or public (9.2) portion
of the class member-specification.
注:
在 class 中声明的静态函数仍然是 class 成员。友元函数不是。
在一个类中,如果函数在不同的说明符(如 private、protected 或 public)中声明为 friend,那么有什么区别。据我了解,朋友功能不是成员。因此,这应该无关紧要。但是,如果我看到 static - 它也不是成员,但访问说明符很重要。所以,我有点困惑。所有这些代码如何正常工作?下面的类有区别吗?
/** Private friend function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
};
/** Protected -- Friend Function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
protected:
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
不,没关系。
C++ 标准,第 11.3 / 9 节 [friend.class]
The meaning of the friend declaration is the same whether the friend declaration appears in the private, protected or public (9.2) portion of the class member-specification.
注:
在 class 中声明的静态函数仍然是 class 成员。友元函数不是。