0

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

4

3 回答 3

1

friend关键字仅用于指定函数或其他类是否可以访问该类的私有成员。您不需要类继承或嵌套,因为FriendFunctionTest它是一个全局函数。全局函数在调用时不需要任何类前缀。

来源friend:http: //msdn.microsoft.com/en-us/library/465sdshe (v=vs.80).aspx

于 2012-09-06T03:34:34.390 回答
0

你真的在这里谈论几个完全不同的事情。以下是其中两个的示例:

1)“朋友”:

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

    // 类声明 class Accumulator { private: int m_nValue; 公共:累加器(){ m_nValue = 0; } void Add(int nValue) { m_nValue += nValue; }

    // 使 Reset() 函数成为此类的朋友 friend void Reset(Accumulator &cAccumulator); };

    // Reset() 现在是 Accumulator 类的朋友 void Reset(Accumulator &cAccumulator) { // 并且可以访问 Accumulator 对象的私有数据 cAccumulator.m_nValue = 0; }

2)“嵌套类”:

于 2012-09-06T03:46:44.120 回答
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

我们已经声明了一个比 std::swap 更有效的交换 Foo 的函数,假设类 Obj1 和 Obj2 具有有效的移动语义。(该死,你用那个绿色复选标记很快!:))

知道因为交换例程由 Foo 对象(在本例中为两个)参数化并在与 Foo 相同的命名空间中声明,所以它成为 Foo 的公共接口的一部分,即使它不是成员也是有用的。该机制称为“依赖于参数的查找”(ADL)。

于 2012-09-06T03:57:51.000 回答