所以我的模板类有一些问题。
<!-- 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();
}
如您所见,这涉及三个步骤:
- 输入
template <....>
,所有模板参数的名称都包含在<
中...>
定义之前。 - 使用
List<T>::Counter
表明Counter
是一个嵌套的类型名 - 使用
typename List<T>::Counter
因为Counter
嵌套到依赖类型中(即依赖于模板参数的类型)。
关于嵌套在模板类中的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041459/