我正在學習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++。
'FriendFunctionTest'不是一個成員函數,因爲你的定義不需要'FriendKeyword ::'。它甚至與'keyObj1'有什麼關係?詳細地說,一旦涉及「friend」,即使函數在類中定義,該函數也不可能成爲該類的成員。 – chris
爲什麼是Java標籤? – Mysticial
這不是朋友的工作方式。它通常在兩個不同的類之間使用,而不是同一類的兩個不同的實例。 – ksming