I want to have two classes, A and B. There is a static function in class B, and A wants to friend this function.
my code is as below
class A
#ifndef A_H_
#define A_H_
#include "B.h"
static void B::staticFunction();
class A {
public:
friend static void B::staticFunction();
A();
virtual ~A();
};
#endif /* A_H_ */
class B
#ifndef B_H_
#define B_H_
#include "A.h"
class B {
public:
static void staticFunction();
B();
virtual ~B();
};
#endif /* B_H_ */
But the compiler tells me:
cannot declare member function 'static void B::staticFunction()'to have static linkage [-fpermissive]
declaration of 'static void B::staticFunction()' outside of class is not definintion [-fpermissive]
what should I do to fix these errors? Thanks in advance for helping me
EDIT
Thanks guys, I finally figured out
the working code is
class A;
class B{
public:
static void staticFunction(A* a);
};
class A {
public:
friend void B::staticFunction(A* a);
A();
virtual ~A();
private:
int i;
};
The most simple example would look like this:
struct A {
static int doit();
};
class B {
static int i;
friend int A::doit();
};
int B::i = 0;
int A::doit()
{
return ++B::i;
}
The order here is important: You first need to define the class that contains the static function that the other class will befriend. For obvious reasons, the definition of that function needs to be delayed until both classes are defined.
You may wish to look up the different meanings of static
in c++, since you are mixing an non-member function static
with an internal-linkage static
.