2015-04-11 9 views
6

मित्र के फ़ंक्शन बॉडी के भीतर नामों के लिए अयोग्य नाम लुकअप कैसे किया जा रहा है? के निम्नलिखित कोड पर विचार करें:मित्र कार्य और स्थिर डेटा सदस्य

#include <iostream> 

void foo(); 

class A 
{ 
    friend void foo(){ std::cout << a << std::endl; } 
    static int a; 
}; 

int A::a = 10; 

int main(){ foo(); } 

DEMO

स्टैंडर्ड राज्यों N4296::7.3.1.2/3 [namespace.memdef] में:

If a friend declaration in a non-local class first declares a class, function, class template or function template the friend is a member of the innermost enclosing namespace.

तो, मैं उम्मीद अयोग्य नाम देखने A::a भी नहीं मिला है, लेकिन यह किया था। मैं जानबूझकर A::a घोषणा में दोस्त की फ़ंक्शन परिभाषा के बाद घोषणा नहीं करता हूं, यह नहीं मिलेगा। मित्र के अयोग्य नाम लुकअप के लिए वास्तविक नियम क्या है?

+0

साफ प्रश्न; मैं * मान रहा हूं * इसे इस तथ्य के साथ करना है कि यह एक दोस्त है, इसलिए यह प्रत्यक्ष माता-पिता के दायरे में अभी भी 'ए' के ​​इन-स्कोप सदस्यों तक पहुंचने में सक्षम है। मैंने पहले कभी नहीं माना है; दिलचस्प खोज – Qix

+0

'मित्र' घोषणा और 'स्थिर 'सदस्य चर के बीच कोई संबंध नहीं है। मुझे नहीं पता कि आप क्यों सोचते हैं कि वे संबंधित हैं। –

+0

@RSahu मैंने अभी स्टैटिक डेटा सदस्यों के लिए अयोग्य नाम लुकअप के बारे में पूछा है, हम सीधे दोस्तों के फ़ंक्शन बोड के भीतर गैर-स्टैस्टिक सदस्यों का उपयोग नहीं कर सकते हैं। –

उत्तर

4

जवाब काफी सरल था:

N4296::3.4.1/8 [basic.lookup.unqual]:

For the members of a class X, a name used in a member function body, in a default argument, in an exceptionspecification, in the brace-or-equal-initializer of a non-static data member (9.2), or in the definition of a class member outside of the definition of X, following the member’s declarator-id31, shall be declared in one of the following ways:

[...]

(8.2) — shall be a member of class X or be a member of a base class of X (10.2),

[...]

N4296::3.4.1/9 [basic.lookup.unqual]:

Name lookup for a name used in the definition of a friend function (11.3) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions.

यह है कि।

युपीडी:

इनलाइन यहाँ महत्वपूर्ण है। यही कारण है कि वर्ग परिभाषा के बाहर परिभाषित दोस्त फ़ंक्शन सीधे कक्षा के स्थिर सदस्यों का उपयोग नहीं कर सकता है। उदाहरण के लिए, निम्नलिखित कोड संकलन-टाइम त्रुटि pritns:

#include <iostream> 

class A 
{ 
    static int a; 
    friend void foo(); 
}; 

int A::a = 10; 

void foo(){ std::cout << a << std::endl; } 



int main(){ foo(); } 

DEMO

+0

मुझे खुशी है कि आपको जवाब मिल गया। :) –

संबंधित मुद्दे