一、++运算符重载
前置++运算符重载
成员函数的方式重载,原型为:函数类型 &operator++();
友元函数的方式重载,原型为:friend 函数类型&operator++(类类型&);
后置自增和后置自减的重载
成员函数的方式重载,原型为:函数类型 &operator++(int); //比前置++多了一个参数,为了区别前置++进行的重载
友元函数的方式重载,原型为:friend函数类型&operator++(类类型&,int);
这里我们实现一个简单的整数运算的例子:
#include <iostream>
using namespace std;
class Integer
{
public:Integer(int n);~Integer();Integer& operator++();//friend Integer& operator++(Integer& i);Integer operator++(int n);//friend Integer operator++(Integer& i, int n);void Display() const;
private:int n_;
};Integer::Integer(int n) : n_(n)
{
}Integer::~Integer()
{
}Integer& Integer::operator ++()
{++n_;return *this;
}Integer Integer::operator++(int n)
{cout<<"编译器传的默认参数:"<<n<<endl;Integer tmp(n_);n_++;return tmp;
}void Integer::Display() const
{cout<<n_<<endl;
}int main(void)
{Integer n(100);n.Display();Integer n2 = ++n; //等价于调用 n.operator++();</span>n.Display();n2.Display();Integer n3 = n++; //等价于调用 n.operator++(0);参数0是由编译器默认产生,为了区别前置后置++,这个参数是dummy变量,我们不会使用它n.Display();n3.Display();return 0;
}
打印结果:
100
101
101
编译器传的默认参数:0
102
101
101
101
编译器传的默认参数:0
102
101
二、!运算符重载和赋值运算符重载
下面是一个String实现的例子:
#include <iostream>
using namespace std;
class String
{
public:explicit String(const char* str="");String(const String& other);String& operator=(const String& other);String& operator=(const char* str);bool operator!() const;~String(void);void Display() const;private:char* AllocAndCpy(const char* str);char* str_;
};String::String(const char* str)
{str_ = AllocAndCpy(str);
}String::String(const String& other)
{str_ = AllocAndCpy(other.str_);
}String& String::operator=(const String& other)//深拷贝
{if (this == &other)return *this;delete[] str_;str_ = AllocAndCpy(other.str_);return *this;
}String& String::operator=(const char* str) //深拷贝
{delete[] str_;str_ = AllocAndCpy(str);return *this;
}bool String::operator!() const
{return strlen(str_) != 0;//字符串不为空即为true
}String::~String()
{delete[] str_;
}char* String::AllocAndCpy(const char* str)
{int len = strlen(str) + 1;char* newstr = new char[len];memset(newstr, 0, len);strcpy(newstr, str);return newstr;
}void String::Display() const
{cout<<str_<<endl;
}int main(void)
{String s1("abc");String s2(s1);String s3;s3 = s1;s3.Display();s3 = "xxxx";s3.Display();String s4;bool notempty;notempty = !s4;cout<<notempty<<endl;s4 = "aaaa";notempty = !s4;cout<<notempty<<endl;return 0;
}