有兩種可能性讓程序編譯。
作爲朋友函數的第一個在類外定義的是使用靜態類數據成員的限定名。例如
test* friendOfTest(){
test::ptr = new test; //Error,ptr not declared in this scope in this line
return test::ptr;
}
第二個是定義類內的函數。在這種情況下,它將在班級範圍內。
根據C++標準(11.3好友)
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).
例如
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;
}
這兩個程序都能成功編譯。
'test :: ptr = new test;' – LogicStuff
'test :: ptr = new test;' – YSC
8秒太晚了> _ <我投票結束這個問題,因爲對別人沒用。 – YSC