There are two possibilities to make the program to compile.
The first one as the friend function is defined outside the class is to use qualified names of the static class data members. For example
test* friendOfTest(){
test::ptr = new test; //Error,ptr not declared in this scope in this line
return test::ptr;
}
The second one is to define the function inside the class. In this case it will be in the scope of the class.
According to the C++ Standard (11.3 Friends)
7 Such a function is implicitly inline. A friend function defined in a
class is in the (lexical) scope of the class in which it is defined. A
friend function defined outside the class is not (3.4.1).
For example
class test{
private:
static test* ptr;
public:
friend test* friendOfTest();
friend test* friendOfTest(){
ptr = new test; //Error,ptr not declared in this scope in this line
return ptr;
}
void someMethod(){ cout<<"someMethod()\n";}
};
Here are demonstrative programs
#include<iostream>
using namespace std;
class test;
test* friendOfTest();
class test{
private:
static test* ptr;
public:
friend test* friendOfTest();
/*
friend test* friendOfTest(){
ptr = new test; //Error,ptr not declared in this scope in this line
return ptr;
}
*/
void someMethod(){ cout<<"someMethod()\n";}
};
test* test::ptr=NULL;
test* friendOfTest(){
test::ptr = new test; //Error,ptr not declared in this scope in this line
return test::ptr;
}
test* friendofTest();
int main(){
test* t;
t = friendOfTest();
t->someMethod();
return 0;
}
and
#include<iostream>
using namespace std;
class test;
test* friendOfTest();
class test{
private:
static test* ptr;
public:
// friend test* friendOfTest();
friend test* friendOfTest(){
ptr = new test; //Error,ptr not declared in this scope in this line
return ptr;
}
void someMethod(){ cout<<"someMethod()\n";}
};
test* test::ptr=NULL;
/*
test* friendOfTest(){
test::ptr = new test; //Error,ptr not declared in this scope in this line
return test::ptr;
}
*/
test* friendofTest();
int main(){
test* t;
t = friendOfTest();
t->someMethod();
return 0;
}
the both programs compile successfully.