2

我做了两个简单的类,只是为了了解朋友类的工作原理。我很困惑为什么这不能编译,Linear 类也可以访问 Queues 类中的结构吗?

线性.h

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

    private:
  };

线性.cpp

#include "Linear.h" 

队列.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>;
    };

队列.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
4

2 回答 2

0

要回答您最初的问题:

类中的friend关键字允许友元函数或类访问声明友元约束的类的私有字段。有关此语言功能的详细说明,请参阅此页面

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

friend class Linear<k,v>;

问问自己,什么是k,它在哪里定义?对v.

基本上,模板不是一个类,它是一个语法结构,让您定义一个“类的类”,这意味着对于模板:

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

你还没有一个类,但是如果你提供一个正确的类型名,它可以让你定义类。在模板中定义了类型名 T,并且可以在适当的位置使用它,就好像它是一个真正的类型一样。

在以下代码片段中:

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

你定义了另一个模板,当用给定的类型名实例化时,它将包含一个具有相同类型名的模板 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>;
};

将友好性限制为仅使用andLinear的该模板的实例,或类似的东西:xx

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

  private:
     struct Nodes{
        int x;
     };

  friend class Linear<k,v>;
};

如果你想允许k并被v随意定义。

于 2012-11-24T19:56:38.697 回答
-1

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

朋友只是意味着该类对访问私有和受保护的限制已被删除。基本上,好像课堂上的私人这个词是公共的。

一定要尝试提交有一个问题的代码,并且除了一件事之外你都理解。

于 2012-11-24T19:17:57.403 回答