声明 C++静态成员函数作为其所在类的友元(语法)
将静态成员函数声明为其所在类的友元
的语法是什么?
class MyClass
{
private:
static void Callback(void* thisptr); //Declare static member
friend static void Callback(void* thisptr); //Define as friend of itself
}
我可以将其折叠成一行吗?
class MyClass
{
private:
friend static void Callback(void* thisptr); //Declare AND Define as friend
}
是否有另一种方法可以将其全部折叠成一行?
回答
请不要投反对票,这源于我对 C++ 静态成员函数缺乏了解。答案是他们不需要成为朋友,他们已经可以访问私人成员。所以我的问题有点无效。
What is the syntax for declaring a static member function as a friend
of the class in which it resides.
class MyClass
{
private:
static void Callback(void* thisptr); //Declare static member
friend static void Callback(void* thisptr); //Define as friend of itself
}
Can I fold it into this one-liner?
class MyClass
{
private:
friend static void Callback(void* thisptr); //Declare AND Define as friend
}
Is there another way to fold it all into a single line?
Answer
Please don't downvote, this stems from my lack of knowledge about C++ static member functions. The answer is that they don't need to be friend, they already can access private members. So my question was somewhat invalid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其实如果是静态的就不用用friend更准确了。静态成员函数可以像普通成员函数一样访问类的内部。唯一的区别是它没有 this 指针。
Actually, no need to use friend if it is static is more accurate. A static member function has access to the internals of the class just like a normal member function. The only difference is it doesn't have a this pointer.
类成员函数不能是其自己类的友元 - 它已经是类成员并且可以访问其私有函数。和它交朋友有什么意义?这不是脸书...
The class member function cannot be a friend of its own class - its already the class member and can access its privates. What' the point in befriending it? Its not Facebook...
默认情况下,静态成员函数可以访问类的
protected
/private
部分,无需将其设为friend
。A static member function has access to the
protected
/private
parts of a class by default, no need to make it afriend
.