[英]How do friend classes interact with each other
我开设了两个简单的班级,目的只是为了了解朋友班级的工作原理。 我对为什么不编译感到困惑,并且Linear类也可以访问Queues类中的结构吗?
线性度
template<typename k, typename v >
class Linear
{
public:
//Can I create a instance of Queues here if the code did compile?
private:
};
线性文件
#include "Linear.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
要回答您的第一个问题:
类内的friend
关键字使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;
上面的代码中的,由包含模板定义 。 但是,在代码中, k
和v
在使用它们的模板中或在顶层都没有这样的定义。
本着同样的精神,以下模板:
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
的友好性限制为仅使用x
和x
或类似这样的模板的实例:
template<typename x,typename k, typename v>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<k,v>;
};
如果要允许k
和v
随便定义。
您的问题是模板而不是该代码中的朋友类。
朋友只是意味着该类取消了禁止访问私有和受保护的限制。 基本上,好像班上的私人一词是公共的。
尝试提交具有一个问题的代码,除了一件事之外,您都会理解所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.