简体   繁体   English

类模板的友元声明

[英]Friend declaration of class template

I'm facing problems with friend class templates.我遇到了朋友类模板的问题。 Here's how my code looks like这是我的代码的样子

template<typename T>
class A{
private:

  template<typename U>
  friend class A;

  int m_num = 0;

public:
//...

};

while尽管

template <typename T>
class B{
private:

  template<typename U>
  friend class B;

  template<typename U>
  friend class A; // Set A as friend class template of B

public:

  template<typename U>
  int GetNumOfA(const A<U>& a){
    return a.m_num; // Cannot Access A's private member!
  }

};

I expected A's private members to be accessible since I declared A as friend class of B. But it couldn't access it.我希望 A 的私有成员可以访问,因为我将 A 声明为 B 的朋友类。但它无法访问它。 Could you help me figure out why this happens?你能帮我弄清楚为什么会这样吗? Or any ideas to make m_num accessible from B?或者有什么想法可以让 B 访问m_num

You have it the wrong way around.你的方法不对。 You want B to be friend of A .您希望B成为A朋友。 So you need to declare B a friend in A 's definition:所以你需要在A的定义中声明B为朋友:

template<typename T>
class A{

//...

  template<typename U>
  friend class B;

//...

};

Do however think about whether you actually want all of these classes and their different specializations to be friend .但是,请考虑一下您是否真的希望所有这些类及其不同的专业化成为friend The point of making a member private is that it represents a state internal to the class and should not be accessed directly by unrelated code.将成员设为private的重点在于它代表类内部的状态,不应由无关代码直接访问。 Usually, if you need direct access to a member, then you should either make it public or if there is a class invariant that doesn't allow that, give access to it through a public member function which preserves the invariant.通常,如果您需要直接访问成员,那么您应该将其设为public或者如果存在不允许这样做的类不变量,请通过保留不变量的public成员函数来访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM