重载操作符号

前几天一同学说去**面试,被问到现场写一个string类出来。

要写出这个类,主要知道几个默认构造函数,这个也是面试中常考的。

第一:拷贝构造函数。string(const string &lhs);

第二:赋值构造函数。string & operator=(const string &lhs)

//这里就有2个问题

第一:赋值构造函数为什么是返回string &//这里是一个引用。

第二,operator=(const string &lhs)这里为啥只有一个参数。

对于第一个问题。我们知道,=(赋值)操作符,在c++语言在的意义是 a=b。

就是b赋值给a。所以,当你构造好这个对象之后,事实上,返回的就是这个对象了,当然是引用了。

第二个问题,为啥只有一个参数呢。

如果operator=操作符是类的成员变量,事实上,他有一个隐藏的函数参数,就是this了。

==============

string.cpp:40: error: `String& operator=(const String&, const String&)' must be a nonstatic member function

//尝试将operator=放到类外面时候,报了这个错。

1 #include<stdio.h>
2 #include<string.h>
3  class String
4 {
5 String(const char *p = NULL)
6 {
7 if(NULL != p)
8 {
9 int strLen = strlen(p);
10 pStr = new char[strLen + 1];
11 strncpy(pStr,p,sizeof(pStr));
12 }
13 else
14 {
15 pStr = new char[1];
16 pStr[0] = 0;
17 }
18 }
19 String(const String &rhs)
20 {
21 int strLen = strlen(rhs.pStr);
22 pStr = new char[strLen + 1];
23 strncpy(pStr,rhs.pStr,sizeof(pStr));
24 }
25 String & operator= (const String &rhs)
26 {
27 if(this == &rhs)
28 return *this;
29 delete [] pStr;
30 int strLen = strlen(rhs.pStr);
31 pStr = new char[strLen + 1];
32 strncpy(pStr,rhs.pStr,sizeof(pStr));
33 return *this;
34 }
35 public:
36 char *pStr;
37 };
 

posted on 2011-07-03 14:28  51Liuda  阅读(307)  评论(0编辑  收藏  举报

导航