朋友类是如何相互作用的
How do friend classes interact with each other
我制作了两个简单的类,只是为了了解友元类是如何工作的。我很困惑为什么这不编译,以及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模板定义。但是,在您的代码中,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
的友好性限制为仅具有friend
0和x
的模板的实例,或者类似的东西:
template<typename x,typename k, typename v>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<k,v>;
};
如果您希望允许随意定义k
和v
。
您的问题是模板,而不是代码中的友元类。
Friend只是意味着该类取消了对访问私有和受保护的限制。就好像课堂上的"私人"一词基本上就是"公共"。
一定要尝试提交有一个问题的代码,并且你只理解一件事。
- 一位朋友将模板函数缩写为clang和gcc
- 班级的朋友是不可接近的
- 与朋友声明相反
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 类似虚拟的朋友功能?
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 在朋友类中使用模板
- 访问私人成员而不使用朋友类
- 类和朋友在它们之间起作用
- "朋友"成员函数和 GCC 与 Clang
- 朋友声明的复杂范围界定规则有什么意义?
- C++:让函数成为多个类的朋友?
- 有没有办法C++将给定类的功能限制为仅另一个类(不使用继承,朋友)?
- 朋友,前瞻宣言,C++
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- Kotlin、NDK和C++的相互作用
- 限制多模板参数朋友函数可访问的类实例的范围
- 朋友定义函数的名称空间是什么
- 朋友函数随机行为
- 朋友类是如何相互作用的