String 类的拷贝构造函数, 赋值操作符重载, 算数操作符重载

来源:互联网 发布:化工就业数据 编辑:程序博客网 时间:2024/05/18 11:09
一般来讲 赋值,下标,调用 和成员放文件头必须定义为成员函数,否则在编译时会出现错误复合复制操作符通常也应该定义为类的成员(当然不这么做不会出现编译错误)改变对象状态的自增 自减 解引用 应该定义为类成员,对象操作符 (如 算数运算符(返回一个对象,一般不返回引用,与内置操作符的返回类型想匹配),相等操作符,关系操作符,位操作符 最好定义为普通非成员函数)
下面为String类的拷贝构造函数,赋值操作符重载的代码:
#include <iostream>#include <cstring>using namespace std;class String{public:String(const char *str = NULL);String(const String & other);String & operator =  (const String & other);//返回引用是为了减少开销,否则就得调用拷贝构造函数friend String  operator + (const String &, const String & other);// 这里不能返回引用,如果返回引用将报错,
//因为此时函数体里面的temp 临时变量会被释放//friend String  operator - (const String &, const String & other);friend bool operator < (const String &, const String & other);friend bool operator > (const String &, const String & other);friend bool  operator == (const String &, const String & other);friend ostream & operator << (ostream &, const String &);//friend ostream & operator << (ostream &,  String &); // 会改变string 因此不能是const//必须为友元函数,因为输入输出操作符不能成为其他类的成员函数,而且这个函数需要访问string类的私有成员~String();char  *show (){return data;}private:char *data;};String::String(const char *str){if(str == NULL){data = new char[1];data = '\0';}else{int len = strlen(str);data = new char[len+1];strcpy(data, str);}}String::String(const String & other){int len = strlen(other.data);data = new char[len+1];strcpy(data, other.data);}String & String::operator = (const String & other){if(this == &other)return *this;delete [] data;int len = strlen(other.data);data = new char[len+1];strcpy(data, other.data);return *this;}String operator + (const String & first , const String & other){String temp;temp.data = new char[strlen(first.data)+ strlen(other.data) + 1];if(temp.data != NULL)strcpy(temp.data, first.data);strcat(temp.data, other.data);return temp;}bool operator < (const String & first, const String & other){if(strcmp(first.data, other.data) < 0)return true;return false;}bool operator > (const String & first, const String & other ){if(strcmp(first.data, other.data) > 0)return true;return false;}bool operator == (const String & first, const String & other ){if(strcmp(first.data, other.data) == 0)return true;return false;}ostream & operator << (ostream & output, const String & other)// ostream 不能为const 因为对IO对象的读写会改变他的状态,引用必须是非const的{output << other.data;return output;}String::~String(){delete [] data;}int main(){char *p = "abc";cout << strlen(p) << endl;String s(p);cout << "s:" <<s<<endl;String s1 = s;cout << "s1:" << s1<<endl;cout << "s+s1 = " << s+s1 << endl;String s2;s2 = s;cout <<"s2:"<< s2.show() << endl;String s3("xyz");cout << "s3: "<<s3 <<" s>s3: "<<(s>s3)<<" s==s3: "<<(s == s3) <<" s<s3: " <<(s<s3)<<endl;return 0;}


原创粉丝点击