我正在学习 C++,我正在尝试更多地了解如何使用 friend 键盘。
但是,我在头文件中使用嵌套类时遇到问题。
我知道头文件应该只用于声明,但我不想在其中包含一个 cpp 文件,所以我只使用一个头文件来声明和构建。
Anways,我有一个 main.cpp 文件,我希望严格使用它来创建类的对象和访问它的函数。
但是,我不知道如何在我的头文件中创建 FriendFunctionTest 函数,以便我可以在 main.cpp 源文件中使用 header Class 对象访问它,因为我试图理解“friend”关键字。
这是我的标题代码:
#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++。
最佳答案
friend
关键字仅用于指定函数或其他类是否可以访问该类的私有(private)成员。您不需要类继承或嵌套,因为 FriendFunctionTest
是一个全局函数。全局函数在调用时不需要任何类前缀。friend
的来源: http://msdn.microsoft.com/en-us/library/465sdshe(v=vs.80).aspx
关于c++ - 如何在 C++ 中正确使用嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12292554/