注册 登录
编程论坛 C++教室

有关类指针的问题!!

trhuang 发布于 2007-05-15 23:59, 460 次点击

下面的程序我知道不规范,我只是想形象说明一下我的问题.请大家重点回答我的问题,谢!

#include<iostream.h>
#include<stdlib.h>
#include<string.h>
class stu{

public :
int name ;
stu *next;
stu()
{
name=100;
next=NULL;
}
};

void main()

{
stu *top,t;

top=t;

top->name=8;//在指针里我输入一个数

cout<<top-name<<endl;//我以为会输出8!

}

请问我想在一个类的指针下输入一个数,应该怎样做>??


6 回复
#2
kisscjy2007-05-16 00:14

lz,是输出8啊~~~~~
先改正一下你程序里的错误~~~
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
class stu
{

public :
int name ;
stu *next;
stu()
{
name=100;
next=NULL;
}
};


void main()

{
stu *top,t;


top=&t; //top为指针,而t为对象,应该要使指针top指向对象t;


top->name=8;//在指针里我输入一个数


cout<<top->name<<endl;//我以为会输出8!


}
截不了图给你看
但在我的机器上运行是输出8的~~~


#3
trhuang2007-05-17 14:18

#include<iostream.h>
#include<stdlib.h>
#include<string.h>
class stu{

public :
int name ;
stu *next;
stu()
{
name=100;
next=NULL;
}
};
stu* ask(stu *top)
{
stu t;
top=&t;
if(!top)
{cout<<"err"<<endl;
exit(0);
}
return top;
}
stu* input(stu *top)
{
stu *old,*star,t;
cout<<star<<endl;
old=ask(old);
star=ask(star);

cout<<star<<endl;
old=top;
int i=0;
while(i<3)
{
cout<<"name:";

cin>>star->name;
old->next =star;
old=star;
i++;

star=ask(star);
}
return top;


}
void print(stu *top)
{

int i=0;
stu *star;
star=top;
for(i=0;i<3;i++)
{
cout<<"name:"<<star->name<<endl;
star=star->next;
}

}
void main()
{
stu *top,t;
top=&t;
input(top);
print(top);
}

可能是我的思路错了.我想用这种方法把输入的数输出!麻烦你帮帮忙!谢!

#4
kisscjy2007-05-17 18:22
我想问一下你这段代码有什么用 ?

stu* ask(stu *top)
{
stu t;
top=&t;
if(!top)
{cout<<"err"<<endl;
exit(0);
}
return top;
}
#5
kisscjy2007-05-17 19:01

对楼主的代码做了以下修改:
我实在看不懂stu* ask(stu *top)这个函数对整个程序有什么作用
所以只好把它删了

#include<iostream.h>
#include<stdlib.h>
#include<string.h>
class stu
{
public :
int name ;
stu *next;
stu()
{
name=100;
next=NULL;
}
};

stu* input(stu* &top)
{
cout<<"please input name:"<<endl;
stu *p2,*p1;
p2=new stu;
top=0;


for(int i=0;i<3;i++)
{
cin>>p2->name;
if(top==NULL) top=p2;
else p1->next=p2;
p1=p2;
p2=new stu;

}

p1->next=NULL;
delete p2;
return top;
}

void print(stu *top)
{

int i=0;
stu *star;
star=top;
for(i=0;i<3;i++)
{
cout<<"name:"<<star->name<<endl;
star=star->next;
}

}


void main()
{
stu *top;
input(top);
print(top);
}

#6
trhuang2007-05-17 20:05

谢!

1