我正在学习 C++,我正在尝试更多地了解如何使用朋友键盘。
但是,我在头文件中使用嵌套类时遇到问题。
我知道头文件应该只用于声明,但我不想在其中包含一个 cpp 文件,所以我只使用一个头文件来声明和构建。
Anways,我有一个 main.cpp 文件,我希望严格使用它来创建类的对象并访问它的函数。
但是,我不确切知道如何在我的头文件中创建 FriendFunctionTest 函数,以便我可以使用 header Class 对象在 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);
但显然它不起作用,因为 main.cpp 在头文件中找不到 FriendFunctionTest 函数。
我该如何解决这个问题?
我再次道歉,我只是想在线学习 C++。