为什么第一个是对应p[i].而第二个对应p[i]->
我运行了下,为什么第二个运行正确,而第一个能运行但是输入两组数就未响应了?而且我把数组长度N定义为1就都正常了,为什么?
#include<iostream.h>
#include<string.h>
#define N 2
class book
{char name[5]; int sold;
public:
virtual char*getname(char*na)=0;
virtual int getsold(int so)=0;
virtual void printname()=0;
virtual void printsold()=0;
virtual void compare()=0;
};
class master:public book
{char name[5]; int sold;
public:
master(){}
char*getname(char*na){strcpy(name,na);return name;}
int getsold(int so){sold=so;return sold;}
void printname(){
cout<<getname(name)<<endl;}
void printsold(){
cout<<getsold(sold)<<endl;}
void compare(){
if(sold>500){
printname();}}
};
main()
{
magazine n1,n2;
master m1,m2,m3,m4,m5;
char name[N];int sold;
book *p=new master[2]; //?
book *y[2]={&n1,&n2};
// magazine *t[10];
cout<<"输入图书名字和销量:"<<endl;
for(int i=0;i<=N-1;i++){
cin>>name>>sold;
p[i].getname(name); //?
p[i].getsold(sold);
}
cout<<"销量大于500的图书:"<<endl;
for(i=0;i<=N-1;i++){
p[i].compare();}}
////////////////////////////////////////
#include<iostream.h>
#include<string.h>
#define N 2
class book
{char name[5]; int sold;
public:
virtual char*getname(char*na)=0;
virtual int getsold(int so)=0;
virtual void printname()=0;
virtual void printsold()=0;
virtual void compare()=0;
};
class master:public book
{char name[5]; int sold;
public:
// master(char* na,int so):name(na),sold(so){}
char*getname(char*na){strcpy(name,na);return name;}
int getsold(int so){sold=so;return sold;}
void printname(){
cout<<getname(name)<<endl;}
void printsold(){
cout<<getsold(sold)<<endl;}
void compare(){
if(sold>500){
printname();}}
};
main()
{
magazine n1,n2;
master m1,m2,m3,m4,m5;
char name[N];int sold;
book *p[2]={&m1,&m2}; //book *p[2]={&m1,&m1}不可,因为p[i]->getname(name)函数会改变m1的值,使p[1],p[2]值一样,p只是指针,核心为&m1
book *y[2]={&n1,&n2};
// magazine *t[10];
cout<<"输入图书名字和销量:"<<endl;
for(int i=0;i<=N-1;i++){
cin>>name>>sold;
p[i]->getname(name);
p[i]->getsold(sold);
}
cout<<"销量大于500的图书:"<<endl;
for(i=0;i<=N-1;i++){
p[i]->compare();}
}
天蓬老师2017-04-17 14:32:19
I read it wrong before, please revise the answer:
Damn it, it turns out to be such a weird way of writing! ! !
What you new
came out is master[]
, and p
is book*
. How can you assign it to it~
So when written as p[i]
, the memory address found is p+i*sizeof(book)
instead of p+i*sizeof(master)
sizeof(book)
and sizeof(master)
are not equal! So your p[i]
is inexplicably stuck halfway in the memory, and if you operate this strange place as master
, something will obviously go wrong!
As for why no error is reported when N is 1, it is because you only visited one p[0]
at this time. Since i==0
, then the two addresses above are calculated to be the same