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

关于“&”的使用问题

LJCX 发布于 2008-11-25 18:22, 549 次点击
请大家看一下下面这段代码
# include <iostream>
# include <string>
using namespace std;

class myclass
{
  char *p;
public:
  myclass (char *pn)
{
  p = new char[strlen(pn)+1];            // 请问,这个地方为什么需要 +1 ?
  strcpy(p,pn);
}
 ~myclass() { delete p; }
 myclass &operator = (myclass &s)  // 这里是重载赋值运算符,那么蓝色的2个 & 分别起什么作用啊?
{
  delete p;
  p = new char[strlen(s.p)+1];
  strcpy(p,s.p);
  return *this;
}
 void display() {cout<<p<<endl;}
}

void main()
{
  myclass s1("first object");
  myclass s2("second object");
  s2 = s1;
  cout<<"s1 *p=";
  s1.display();
  cout<<"s2 *p=";
  s2.display();
}
2 回复
#2
sunkaidong2008-11-25 18:40
引用,是对你要操作的数据起别名...
#3
p1s2008-11-25 20:06
回答问题1:因为字符串的结尾含有一个结尾符'\0',如果不+1的话就无法存放这个字符串了。(参考《易学C++》第7章字符串的存储)
回答问题2:&表示引用操作,左侧的&表示返回的也是一个引用,这使得返回值能够作为一个左值,或减少不必要的传递。右侧的&表示参数是一个引用,减少不必要的传递。
1