2012-09-06 25 views
0

我正在學習C++,並試圖更多地瞭解如何使用朋友鍵盤。如何在C++中正確使用嵌套類?

但是,我無法在我的頭文件中使用嵌套的類。

我知道頭文件應該只用於聲明,但我不想包含一個cpp文件,所以我只是使用頭文件來聲明和構建。

反正,我有一個main.cpp文件,我希望嚴格地用於創建類的對象和訪問其功能。

但是,我不知道如何創建FriendFunctionTest函數在我的頭文件中,我可以在我的main.cpp源文件中使用頭類對象訪問它,因爲我試圖瞭解「朋友」關鍵字。

這裏是我的頭代碼:

#ifndef FRIENDKEYWORD_H_ 
#define FRIENDKEYWORD_H_ 

using namespace std; 

class FriendKeyword 
{ 
    public: 
     FriendKeyword() 
     {//default constructor setting private variable to 0 
      friendVar = 0; 
     } 
    private: 
     int friendVar; 

    //keyword "friend" will allow function to access private members 
    //of FriendKeyword class 
    //Also using & in front of object to "reference" the object, if 
    //using the object itself, a copy of the object will be created 
    //instead of a "reference" to the object, i.e. the object itself 
    friend void FriendFunctionTest(FriendKeyword &friendObj); 
}; 

void FriendFunctionTest(FriendKeyword &friendObj) 
{//accessing the private member in the FriendKeyword class 
    friendObj.friendVar = 17; 

    cout << friendObj.friendVar << endl; 
} 

#endif /* FRIENDKEYWORD_H_ */ 

在我的main.cpp文件,我想要做這樣的事情:

FriendKeyword keyObj1; 
FriendKeyword keyObj2; 
keyObj1.FriendFunctionTest(keyObj2); 

但顯然它不會因爲主要工作。 cpp不能在頭文件中找到FriendFunctionTest函數。

如何解決此問題?

我再次道歉,我只是想在線學習C++。

+1

'FriendFunctionTest'不是一個成員函數,因爲你的定義不需要'FriendKeyword ::'。它甚至與'keyObj1'有什麼關係?詳細地說,一旦涉及「friend」,即使函數在類中定義,該函數也不可能成爲該類的成員。 – chris

+1

爲什麼是Java標籤? – Mysticial

+0

這不是朋友的工作方式。它通常在兩個不同的類之間使用,而不是同一類的兩個不同的實例。 – ksming

回答

1

friend關鍵字僅用於指定函數或其他類是否可以訪問該類的私有成員。您不需要類繼承或嵌套,因爲FriendFunctionTest是一個全局函數。全局函數在調用時不需要任何類前綴。

來源爲friendhttp://msdn.microsoft.com/en-us/library/465sdshe(v=vs.80).aspx

+0

謝謝先生!它現在可以工作,那麼究竟是什麼讓一個函數成爲全局的? – user1631224

+0

@ user1631224:以「全局」表示非成員。 –

+0

全局函數未封裝在命名空間或類中。 – willkill07

0

你真的在談論一些完全不同的東西在這裏。下面是其中的兩個例子:

1) 「朋友」:

  • http://www.learncpp.com/cpp-tutorial/813-friend-functions-and-classes/

    //類聲明 類累加器{ 私人: INT m_nValue; public: Accumulator(){m_nValue = 0; } void Add(int nValue){m_nValue + = nValue; }

    //使Reset()函數成爲這個類的朋友 friend void Reset(Accumulator & cAccumulator); };

    //復位()現在是累加器類 無效復位(累加器& cAccumulator) {// 並且可以訪問累加器的私有數據對象 cAccumulator的朋友。m_nValue = 0; }

2) 「的嵌套類」:

0

朋友是不是成員。以下是在實踐中如何使用「朋友」的一個很好的例子。

namespace Bar { 

class Foo { 

    public: 
     // whatever... 

    friend void swap(Foo &left, Foo &right); // Declare that the non-member function 
              // swap has access to private section. 
    private: 
     Obj1 o1; 
     Obj2 o2; 
}; 

void swap(Foo &left, Foo &right) { 
    std::swap(left.o1, right.o1); 
    std::swap(left.o2, right.o2); 
} 

} // end namespace Bar 

我們已經宣佈對換Foo的比STD更有效的功能::交換會是這樣,假設類OBJ1和OBJ2,具有高效運行的語義。 (請注意,你用這個綠色的複選標記:) :)

知道由於交換例程由Foo對象(在本例中爲兩個)參數化並且在相同的命名空間中聲明爲Foo,它成爲Foo的公共接口的一部分,即使它不是成員。該機制被稱爲「參數依賴查找」(ADL)。