运算符重载03 -- = 和!
MyString.h
- #ifndef _MY_STRING_H_
- #define _MY_STRING_H_
- class MyString
- {
- public:
- // explicit 修饰后的构造函数,不能进行隐示转换
- explicit MyString(const char* str = "");
- //深拷贝
- MyString(const MyString& other);
- // =号运算符重载
- MyString& operator = (const MyString& other);
- MyString& operator = (const char* str);
- // ! 非运算符重载
- bool operator !()const;
- ~MyString();
- void display();
- private :
- char* AllocAndCpy(const char* str);
- char* str_;
- };
- #endif //_MY_STRING_H_
- #pragma warning(disable:4996)//屏蔽错误提示
- #include "MyString.h"
- #include <iostream>
- #include <string.h>
- using namespace std;
- MyString::MyString(const char* str)
- {
- cout<<"MyString("<<str<<")"<<endl;
- str_ =AllocAndCpy(str);
- }
- MyString::~MyString()
- {
- //new出来的就要释放掉
- delete[] str_;
- }
- MyString::MyString(const MyString& other){
- cout<<"MyString(const MyString& other)("<<other.str_<<")"<<endl;
- str_ =AllocAndCpy(other.str_);
- }
- char* MyString::AllocAndCpy(const char* str){
- //计算长度
- int len =strlen(str);
- //分配空间
- char* newnewchar = new char[len];
- memset(newchar,0,len);
- //进行copy
- strcpy(newchar,str);
- return newchar;
- }
- void MyString::display(){
- cout<<str_<<endl;
- }
- MyString& MyString::operator=(const MyString& other){
- cout<< "= operation"<<endl;
- if(this == &other){
- return *this;
- }
- delete [] str_;
- str_= AllocAndCpy(other.str_);
- return *this;
- }
- MyString& MyString::operator = (const char* str){
- str_= AllocAndCpy(str);
- return *this;
- }
- bool MyString::operator !()const{
- return strlen(str_)!=0;
- }
转载于:https://blog.51cto.com/vincenttung/1172492