编译程序有两种可能。
第一个作为友元函数在类外定义是使用静态类数据成员的限定名。例如
test* friendOfTest(){
test::ptr = new test; //Error,ptr not declared in this scope in this line
return test::ptr;
}
第二个是在类内部定义函数。在这种情况下,它将在类的范围内。
根据 C++ 标准(11.3 朋友)
7 这样的函数是隐式内联的。定义在 a 中的友元函数
类在定义它的类的(词法)范围内。一种
类外定义的友元函数不是 (3.4.1)。
例如
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";}
};
这里是演示程序
#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;
}
和
#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;
}
两个程序都编译成功。