朋友类如何相互交互

时间:2012-11-24 19:11:57

标签: c++

我有两个简单的课程,我只是为了理解朋友班的工作原理。我很困惑为什么这不编译,而且Linear类是否可以访问Queues类中的struct?

Linear.h

template<typename k, typename v >
 class Linear
 {
    public:
    //Can I create a instance of Queues here if the code did compile? 

    private:
  };

Linear.cpp

#include "Linear.h" 

Queues.h

 #include "Linear.h"

 template<typename k, typename v >
 class Linear;

  template<typename x>
  class Queues
  {
    public:

    private:
        struct Nodes{
            int n;
        };
    //Does this mean I am giving Linear class access to all of my Queues class variable or    is it the opposite ? 
    friend class Linear<k,v>;
    };

Queues.cpp

  #include"Queues.h" 

我的错误是

Queues.h:15: error: `k' was not declared in this scope
Queues.h:15: error: `v' was not declared in this scope
Queues.h:15: error: template argument 1 is invalid
Queues.h:15: error: template argument 2 is invalid
Queues.h:15: error: friend declaration does not name a class or function

2 个答案:

答案 0 :(得分:0)

回答你的初步问题:

类中的friend关键字让friend函数或类访问声明了friend约束的类的私有字段。 有关此语言功能的详细说明,请参阅此page

关于代码中的编译错误: 在这一行:

friend class Linear<k,v>;

问问自己,k是什么,它定义在哪里?与v相同。

基本上,模板不是一个类,它是一个语法结构,允许你定义一个“类类”,这意味着模板:

template <typename T>
class C { /* ... */ };

你还没有一个类,但如果你为它提供了一个合适的类型名,你就可以定义类。在模板中,定义了类型名称T,并且可以像使用真实类型一样使用它。

在以下代码段中:

template <typename U> 
class C2 {
   C<U> x;
   /* ... */
};

定义另一个模板,当使用给定的typename实例化时,它将包含具有相同typename的模板C的实例。上面代码行U中的类型名C<U> x;由包含模板定义。但是,在您的代码中,kv没有这样的定义,无论是在使用它们的模板中,还是在顶层。

本着同样的精神,以下模板:

template <typename U> 
class C2 {
   friend class C<U>;
   /* ... */
};

实例化时,将具有类模板C的实例(同样具有相同的参数U)作为朋友。据我所知,对于所有可能的参数组合,不可能让类模板实例成为给定类的朋友(C ++语言还不支持存在类型)。

例如,您可以编写如下内容:

template<typename x>
class Queues
{
  public:

  private:
     struct Nodes{
        int x;
     };

  friend class Linear<x,x>;
};

Linear的友好性仅限于xx的该模板的实例,或类似的内容:

template<typename x,typename k, typename v>
class Queues
{
  public:

  private:
     struct Nodes{
        int x;
     };

  friend class Linear<k,v>;
};

如果您想允许自由定义kv

答案 1 :(得分:-1)

您的问题是模板中没有该代码中的朋友类。

朋友只是意味着删除了对该类的访问private和protected的限制。好像班里私有这个词基本上是公开的。

尝试提交有一个问题的代码,并且除了一件事以外,你只能理解。

相关问题