嵌套在模板类中的 C++ 类

标签 c++

所以我的模板类有一些问题。

<!-- language: lang-c++ -->

template<class T>
class List {
  class Counter
  {       
    T real;
    T imaginary;
    Counter *next;
 //....
  public:
    Counter(T a=0,T b=0);                  
    virtual ~Counter();                     
    friend ostream& operator<<(ostream&,Counter&);
    friend ostream& operator<<(ostream&,List&);
  };
  Counter* first;
  Counter* last;
//....
};

但是我在方法上遇到了一些问题。如果我将函数写为

template<class T> Counter operator/(Counter &one,...)  

当我查看 VC++10 中的 Counter 时,它会显示类似内容

<error_type>&one
例如。我应该使用 template<class T>我的 Counter 类在代码中随处可见吗?

//Methods
//Counter. For example some methods
Counter operator/(Counter& one,Counter& two){}
ostream& operator<<(ostream&os,Counter&x){}
istream& operator>>(istream&is,Counter&x){}
 //List
template<class T>void List<T>::add(Counter *T,int i,bool c){}

最佳答案

这取决于您是否在类定义的内部定义运算符(无论它们是成员函数还是全局运算符)。

如果您在类定义中执行此操作,则不需要 template<T> ,也不适合 List<T> :

template <typename T>
class List
{
public:
  class Counter
  {
    /* This is a global operator* defined inside the class, and
       as friend. */
    friend Counter operator*(const Counter &c1, const Counter &c2)
    {
      return Counter();
    }
  };

};

(请注意,我对 operator* 的定义实际上并没有用,因为它总是返回一个空的 Counter 对象。这只是为了演示语法。)

但是,如果您在类外部定义运算符(因此也在 List 的模板定义外部),则必须使用函数模板定义的完整语法:

template <typename T>
typename List<T>::Counter operator/(const typename List<T>::Counter &c1, const typename List<T>::Counter &c2)
{
  return List<T>::Counter();
}

如您所见,这涉及三个步骤:

  1. 输入template <....> ,所有模板参数的名称都包含在 < 中... >定义之前。
  2. 使用List<T>::Counter表明Counter是一个嵌套的类型名
  3. 使用typename List<T>::Counter因为Counter嵌套到依赖类型中(即依赖于模板参数的类型)。

关于嵌套在模板类中的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041459/

相关文章:

c++ - QML 中的着色器插件安装

c++ - 为什么不是我可以加载(打开)的所有 DLL 模块?

c++ - 在函数中绘制图像

c++ - 集合中的智能指针多态性

c++ - 如何使用 QSignalMapper 发送自定义结构的实例?

c++ - 在linux上每10ms定期执行一个函数

c++ - 我们什么时候以及为什么需要使用 COM?

c++ - Bool 在 `std::rel_ops` 示例中强制转换?

c++ - 如何在子目录中搜索文件?

c++ - memcmp 为相同(零值)位字段结构返回非零