C++標(biāo)準(zhǔn):
3. A function first declared in a friend declaration has
external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1).
按照
3中說(shuō)的,下面代碼是應(yīng)該通過(guò)的
class?X
{
????friend?void?f();?
};
int?main()
{
????f();?//因?yàn)轭怷中的友元函數(shù)f的聲明有外部鏈接,所以,f可見(jiàn)
}
void?f()?{?/*?ok?to?define?friend?function?in?the?class?body?*/?}
編譯測(cè)試:
VC2005/2010通過(guò) ,而GCC 4.4.3報(bào)錯(cuò):無(wú)法找到名字f
5. A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8),the function name is unqualified, and the function has namespace scope.
[Example:
class M {
? ? friend void f() { } //
definition of global f, a friend of M,
? ? ? ? ? ? ? ? ? ? ? ? // not the definition of a member function
};
—end example]
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).
按照
5中說(shuō)的,既然在類中定義友元函數(shù)f,是"definition of global f",那么也就可以理解為下面的代碼是可以通過(guò)編譯的
class?X
{
????friend?void?f(){?/*?ok?to?define?friend?function?in?the?class?body?*/?}
};
int?main()
{
????f();?
}?
然而VC2005/2010和GCC4.4.3都不能通過(guò)
TCPL中對(duì)友元有如下說(shuō)明:
? “一個(gè)友元聲明不會(huì)給外圍的作用域引進(jìn)一個(gè)名字”?
? “一個(gè)友元函數(shù)或者需要在某個(gè)外圍作用域里顯式聲明,或者以它的類或由該類派生的類作為一個(gè)參數(shù)(13.6節(jié)),否則就無(wú)法調(diào)用這個(gè)友元了。”
C++ primer有如下:
? “友元聲明將已命名的類或非成員函數(shù)引入到外圍作用域中。此外,友元函數(shù)可以在類的內(nèi)部定義,該函數(shù)的作用域擴(kuò)展到包圍該類定義的作用域。”?
? “用友元引入的類名和函數(shù)(定義或聲明),可以像預(yù)先聲明的一樣使用”
C++ primer中的例子:
class X {
? ? ? ? friend class Y;
? ? ? ? friend void f() { /* ok to define friend function in the class body */ }
};
class Z {
? ? ? ? Y *ymem; // ok: declaration for class Y introduced by friend in X
? ? ? ? void g() { return ::f(); } // ok: declaration of f introduced by X
};
標(biāo)準(zhǔn)中說(shuō)的和C++ PRIMER一樣,而和TCPL不一樣。
至于編譯器,GCC做的和TCPL說(shuō)的一樣,而VC和標(biāo)準(zhǔn)說(shuō)的部分一樣(對(duì)于在友元聲明出定義函數(shù)處有出入)
個(gè)人總結(jié)
兩個(gè)編譯器行為不同,所以盡量提前聲明友元所聲明的名字
以上只是個(gè)人的看法,如果有不對(duì)的地方,
懇請(qǐng)各位大大指正
posted on 2010-03-07 10:49
zhaoyg 閱讀(487)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C/C++學(xué)習(xí)筆記