C++ 好友类如何相互交互
我制作了两个简单的类来理解friend类是如何工作的。我不明白为什么这不能编译,线性类是否可以访问Queues类内部的struct 线性hC++ 好友类如何相互交互,c++,C++,我制作了两个简单的类来理解friend类是如何工作的。我不明白为什么这不能编译,线性类是否可以访问Queues类内部的struct 线性h template<typename k, typename v > class Linear { public: //Can I create a instance of Queues here if the code did compile? private: }; 队列 #include "Linear
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"
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.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只是意味着对该类访问private和protected的限制被删除。好像课堂上的private这个词基本上是公共的
请尝试提交有一个问题的代码,并且您只了解一件事。您的问题在于模板,而不是代码中的友元类 Friend只是意味着对该类访问private和protected的限制被删除。好像课堂上的private这个词基本上是公共的
请尝试提交只有一个问题的代码,并且您只了解一件事。要回答您最初的问题: 类中的
friend
关键字允许friend函数或类访问声明friend约束的类的其他私有字段。
有关此语言功能的详细说明,请参见此
关于代码中的编译错误:
在这方面:
friend class Linear<k,v>;
你们还并没有一个类,但若你们提供了一个合适的类型名,那个么它将允许你们定义这个类。在模板中定义了类型名T,并且可以像使用真实类型一样就地使用
在以下代码段中:
template <typename U>
class C2 {
C<U> x;
/* ... */
};
实例化时,将类模板C的实例(同样具有相同的参数U
)作为好友。据我所知,不可能让类模板实例与给定类为朋友,对于所有可能的参数组合(C++语言不支持存在类型)。
例如,您可以编写如下内容:
template<typename x>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<x,x>;
};
如果要允许临时定义
k
和v
要回答您最初的问题:
类中的friend
关键字允许friend函数或类访问声明friend约束的类的其他私有字段。
有关此语言功能的详细说明,请参见此
关于代码中的编译错误:
在这方面:
friend class Linear<k,v>;
你们还并没有一个类,但若你们提供了一个合适的类型名,那个么它将允许你们定义这个类。在模板中定义了类型名T,并且可以像使用真实类型一样就地使用
在以下代码段中:
template <typename U>
class C2 {
C<U> x;
/* ... */
};
实例化时,将类模板C的实例(同样具有相同的参数U
)作为好友。据我所知,不可能让类模板实例与给定类为朋友,对于所有可能的参数组合(C++语言不支持存在类型)。
例如,您可以编写如下内容:
template<typename x>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<x,x>;
};
如果要允许临时定义
k
和v
你没有课。你有模板,没有类。你有模板。
template<typename x>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<x,x>;
};
template<typename x,typename k, typename v>
class Queues
{
public:
private:
struct Nodes{
int x;
};
friend class Linear<k,v>;
};