从模板化类分配运算符访问私有成员变量

从模板化类分配运算符访问私有成员变量

本文介绍了从模板化类分配运算符访问私有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板化的容器类。我正在重载赋值运算符,以便也可以分配派生类型。

I have a container class that is templatized. I am overloading the assignment operator such that derived types can also be assigned.

我的问题是,当类型不同时,我无法访问该类型的私有成员。容器类。获得访问权限的最佳方法是什么?成员变量 不能通过公共获取器访问。

My problem is, when the type is not the same, I cannot access the private members of the container class. What is the best approach to gaining access? The member variables cannot be made accessible through public getters. Thanks!

示例代码:

// Note: var is private

template <class T>
Container<T>& Container<T>::operator=(const Container<T>& rhs) {
   if(*this != rhs) var = rhs.var; // works for same type
   return *this;
}

template <class T>
template <typename U>
Container<T>& Container<T>::operator=(const Container<U>& rhs) {
   if(*this != rhs) var = rhs.var; // does NOT work for different types
   return *this;
}


推荐答案

因为要访问私有实例化了不同类型的模板类的成员,您必须将其他模板作为模板类的好友:

Since you want to access private members of template class instantiated with different types, you've to make other templates as friend of the template class as:

template <class T>
class Container
{
      template<class U>
      friend class Container;

};

请注意,如果 T U 是不同的类型,然后是 Container< T> Container< U> 是两个完全不同的类;如果您不与其他人成为朋友,则无法访问其他人的私人成员。

Note that if T and U are different types, then Container<T> and Container<U> are two completely different classes; one cannot access private members of other if you don't make friend one of other.

还请注意,在上面的代码中,所有实例化班级模板是彼此的朋友。也就是说,如果使用 char int short ,然后

Also note that in the above code all instantiations of the class template are friend of each other. That is, if you instantiate it with char, int, short, then


  • Container< int> 将成为这两个 Container< char> Container< short>

  • Container< char> 将成为 Container< int> 的朋友和 Container< short>

  • Container< short> 将成为 Container< int> 的朋友和 Container< char>

  • Container<int> will be friend of both Container<char> and Container<short>.
  • Container<char> will be friend of both Container<int> and Container<short>.
  • Container<short> will be friend of both Container<int> and Container<char>.

有趣的短语是:彼此的朋友 。通常不会发生这种情况。例如,如果您有一个这样的班级:

The interesting phrase here is : "friend of each other". Usually this doesn't happen. For example, if you have a class like this:

class A
{
   friend class B;
};

然后在这里只有 B A A 不是 B 的朋友。他们不是彼此的朋友 B 可以访问 A 的私有成员,但是 A 无法访问访问 B 的私人成员。 这是此类与上面的模板类之间的区别。

Then here only B is friend of A. A is NOT friend of B. They're NOT "friend of each other". B can access private members of A, but A cannot access private members of B. That is the difference between this class and the template class above.

这篇关于从模板化类分配运算符访问私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:17