64,654
社区成员
发帖
与我相关
我的任务
分享
template< class anytype >
struct node
{
anytype value;
node* next; //指向下个结点
};
list类声明如下template< class anytype >
class list
{
public:
list()
{
count = 0;
head.next = NULL;
}
~list()
int get_count()
{
return count;
}
void add();
void add( const anytype c );
void add( const anytype p[], int n );
void add( const int p[], char n, char current );
bool dlt( int i );
void go_through(); //遍历
bool insert( int i, const anytype c );
void clear();
anytype & operator [] ( int i );
int seek( const anytype model ); //返回值-1表示没找到
private:
node<anytype> head; //头结点,不用来存储数据
int count; //链表结点个数
};
我主要要解决add()函数的问题,第一个无参的add定义如下template< class anytype >
void list<anytype>::add()
{
node<anytype>* p = &head;
while ( p -> next != NULL )
p = p -> next;
p -> next = new node<anytype>;
// p -> next -> value = c;
p -> next -> next = NULL;
count++;
}
无参的add()负责在链表尾部添加一个未赋值的结点(赋值语句被注释掉),add()可以处理任意维数的list类,比如list<int>和list< list<int> >,前者添加一个node<int>结点,后者添加一个node< list<int>结点,这样的话可以创建任意维数的对象,例如三维的list< list< list<int> > >可以作为三位数组来使用。但是通过这样的方式来定义多维数组比较慢,比如3*3的二维链表list< list<int> > a,template< class anytype >
void list< anytype >::add( const int p[], char n, char current ) //p[]数组存储
//每维的结点数,比如p[] = { 4, 3 },表示二维四个结点,一维三个结点,相当于int[4][3]的数组
//n代表p的数组上限,也就是最大维数,current代表函数当前处理的维数,用于递归控制
{
if ( current >= 2 )
{
int number = p[n - current];
for ( int i = 1; i <= number; i++ )
{
add();
( operator [] ( i ) ).add( p, n, current - 1 );
}
}
else
{
int number = p[n - current];
for ( int i = 1; i <= number; i++ )
add();
}
}
operator[](i)函数返回链表中第i个结点的value值,对于二维链表list< list<int> > a,f:\c\test\diy.h(137) : error C2228: left of '.add' must have class/struct/union type
f:\c\test\diy.h(69) : while compiling class-template member function 'void __thiscall list<int>::add(const int [],char,char)'
我的理解是系统认为( operator [] ( i ) ),就是比当前对象低一维的对象不是结构体,而我做如下改动,就不会报错,但却没办法递归了template< class anytype >
void list< anytype >::add( const int p[], char n, char current )
{
if ( current >= 2 )
{
int number = p[n - current];
for ( int i = 1; i <= number; i++ )
{
add();
( operator [] ( i ) ).add(/* p, n, current - 1*/);
}
}
else
{
int number = p[n - current];
for ( int i = 1; i <= number; i++ )
add();
}
}
我想可能是递归的使用让电脑无法判断( operator [] ( i ) )是否还是list对象,请问怎么解决这个问题,如果可以我很多问题都能迎刃而解?