朋友类是如何相互作用的

How do friend classes interact with each other

本文关键字:相互作用 朋友      更新时间:2023-10-16

我制作了两个简单的类,只是为了了解友元类是如何工作的。我很困惑为什么这不编译,以及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:
};

Linear.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>;
};

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

回答您的初始问题:

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

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

friend class Linear<k,v>;

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

基本上,模板不是一个类,它是一个语法结构,可以让你定义一个"类的类",这意味着对于模板:

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

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

在以下代码片段中:

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

您定义了另一个模板,当使用给定的类型名进行实例化时,该模板将包含具有相同类型名的模板C的实例。上面代码的C<U> x;行中的类型名U由include模板定义。但是,在您的代码中,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的友好性限制为仅具有friend0和x的模板的实例,或者类似的东西:

template<typename x,typename k, typename v>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<k,v>;
};

如果您希望允许随意定义kv

您的问题是模板,而不是代码中的友元类。

Friend只是意味着该类取消了对访问私有和受保护的限制。就好像课堂上的"私人"一词基本上就是"公共"。

一定要尝试提交有一个问题的代码,并且你只理解一件事。