关于内嵌依赖类型的问题
前两天作练习题的时候遇到了这样的一个问题:
//头文件screen.h
#ifndef SCREEN_H
#define SCREEN_H
#include<iostream>
#include<string>
template<int hi,int wid>
class Screen
{
public:
typedef std::string::size_type index;
Screen();
Screen(const std::string&);
//复制控制成员
Screen(const Screen&);
~Screen();
Screen operator=(const Screen&);
//其他成员函数
char get()const;
char get(index,index)const;
index get_cursor()const;
bool move(index,index)const;
bool set(char);
std::ostream& display(std::ostream&);
std::ostream& display(std::ostream&)const;
private:
std::string contents;
index cursor;
index height,width;
};
#endif
//定义文件screen.cpp
#include"Screen.h"
using namespace std;
template<int hi,int wid>
Screen<hi,wid>::Screen():
contents(hi*wid),cursor(0),height(hi),width(wid){}
template<int hi,int wid>
Screen<hi,wid>::Screen(const string&str):
contents(str),cursor(0),height(hi),width(wid){}
template<int hi,int wid>
Screen<hi,wid>::Screen(const Screen& sc):
contents(sc.contents),cursor(sc.cursor),height(sc.cursor),width(sc.width){}
template<int hi,int wid>
Screen<hi,wid>::~Screen()
{
}
template<int hi,int wid>
Screen<hi,wid> Screen<hi,wid>::operator=(const Screen&sc)
{
if(!(this->contents==sc.contents&&
this->cursor=sc.cursor&&
this->height=sc.height&&
this->width=sc.width))
{
this->contents=sc.contents;
this->cursor=sc.cursor;
this->height=sc.height;
this->width=sc.width;
}
return *this;
}
template<int hi,int wid>
char Screen<hi,wid>::get()const
{
return contents[cursor];
}
template<int hi,int wid>
char Screen<hi,wid>::get(index h,index w)const
{
if(h>height||w>width)
{
return '\0';
}
else
{
return contents[(h-1)*width+w-1];
}
}
//注意这个函数成员的定义:
template<int hi,int wid>
Screen<hi,wid>::index Screen<hi,wid>::get_cursor()const
{
return cursor;
}
template<int hi,int wid>
bool Screen<hi,wid>::move(index h,index w)const
{
if(h>height||w>width)
{
return false;
}
else
{
cursor=(h-1)*width+wid-1;
return true;
}
}
template<int hi,int wid>
bool Screen<hi,wid>::set(char c)
{
if(width==0||height==0)
return false;
else
{
contents[cursor]=c;
return true;
}
}
template<int hi, int wid>
ostream& Screen<hi,wid>::display(ostream&os)
{
for(int i=0;i<height*width;++i)
{
os<<contents[i];
if((i+1)%width==0)
{
os<<'\n';
}
}
return os;
}
template<int hi, int wid>
ostream& Screen<hi,wid>::display(ostream&os)const
{
for(int i=0;i<height*width;++i)
{
os<<contents[i];
if((i+1)%width==0)
{
os<<'\n';
}
}
return os;
}
编译器报错为:
error: expected constructor, destructor, or type conversion before "Screen"
||=== Build finished: 1 errors, 0 warnings ===|
我看了之后,想到了这个错误,我曾经好像见过,于是在
Screen<hi,wid>::index Screen<hi,wid>::get_cursor()const 这句之前加了一个关键字:typename
(这句就变成了:typename Screen<hi,wid>::index Screen<hi,wid>::get_cursor()const 这个样子)
然后再编译,就通过了。
我知道这个错误是关于,内嵌依赖类型的问题。
于是,我找出我曾经读过的C++ Primer和C++ 必知必会 这两本书,找到其中关于内嵌依赖类型的讲解,
但是这两本书中的讲解都是说:依赖于模板形参,嵌套于类中的类型使用时候要加关键字:typename
但是上面的那个类模板中的index却不是依赖于模板形参的呀,为什么还要加关键字typename呢?
还有就是书中所说的“嵌套于类中”这几个字中的“类”字指的是我定义的那个类,还是指的是作为模板形参的实参的那个类?