将C ++静态成员函数声明为其所在类的朋友(语法)

时间:2011-12-31 01:59:37

标签: c++ syntax friend static-members

将静态成员函数声明为其所在类的friend的语法是什么。

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
}

还有另一种方法可以将它们全部折叠成一行吗?

答案

请不要downvote,这源于我对C ++静态成员函数缺乏了解。答案是他们不需要朋友,他们已经可以访问私人会员了。所以我的问题有点无效。

3 个答案:

答案 0 :(得分:5)

实际上,如果是静态则不需要使用朋友更准确。静态成员函数可以像普通成员函数一样访问类的内部。唯一的区别是它没有这个指针。

void MyClass::Callback(void* thisptr) {
    MyClass* p = static_cast<MyClass*>(thisptr);
    p->public_func(); // legal
    p->private_func(); // legal
    p->private_int_var = 0; // legal
}

答案 1 :(得分:2)

类成员函数不能是它自己的类的朋友 - 它已经是类成员并且可以访问它的私有。交友有什么意义?它不是Facebook ......

答案 2 :(得分:2)

默认情况下,静态成员函数可以访问类的protected / private部分,无需将其设为friend

#include <iostream>

struct Foo{
  Foo(int i) : an_int(i) {}

  static void print_an_int(Foo& self){
    std::cout << self.an_int;
  }
private:
  int an_int;
};

int main(){
  Foo f(5);
  Foo::print_an_int(f); // output: 5
}