c++ - 如何在 C++ 中正确使用嵌套类?

标签 c++

我正在学习 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/

相关文章:

c++ - libgomp缺少: install c++ compiler in home directory?

c++ - 调试 'terminate called after throwing an instance of ...' ,当异常_should_ 被捕获时

c++ - 是否可以将名称附加到 C++ 中的运行时类?

android - liquidfun 1.1.0 ndk-build 2 编译错误

c++ - 为什么 jeprof 评估的 jemalloc 内存配置文件似乎显示所有内存分配?

c++ - 调用模板成员函数编译失败

c++ - C/C++ strcmp 无法将参数 1 从 'char' 转换为 'const char *'

c++ - Cin 在 while 和 for 循环中被忽略

c++ - 在 Boost::bimap 中使用指针

c++ - 作为非类型参数的局部变量,具有模板规范