什么时候必须加&,什么时候又不用,例如下面两段程序,第一段没问题,第二段运行错,必须在形参x前加&。
#include <iostream.h>
class tr
{
private:
int i;
public:
tr(int n);
int get();
};
tr::tr(int n)
{
i=n;
}
int tr::get()
{
return i;
}
void dsp(tr t)
{
cout<<t.get()<<endl;
}
int main()
{
tr t_r(10);
dsp(t_r);
return 0;
}
第二段:
#include <iostream.h>
#include <string.h>
class people
{
private:
char *name;
int age;
public:
people(char *namestr,int i);
~people();
char *getname();
int getage();
};
people::people(char *namestr,int i)
{
name=new char[strlen(namestr)+1];
strcpy(name,namestr);
age=i;
}
people::~people()
{
delete name;
}
char *people::getname()
{
return name;
}
int people::getage()
{
return age;
}
void display(people x)
{
cout<<"people\'s name: "<<x.getname()<<endl;
cout<<"people\'s age: "<<x.getage()<<endl;
}
int main()
{
people p("xieyi",30);
display(p);
return 0;
}