++运算符重载
#ifndef _INTEGER_H_
#define _INTEGER_H_
class Integer
{
public:
Integer(int n);
~Integer();
Integer& operator++();
Integer operator++(int n);
void Display() const;
private:
int n_;
};
#endif
#include "Integer.h"
#include <iostream>
using namespace std;
Integer::Integer(int n) : n_(n)
{
}
Integer::~Integer()
{
}
Integer& Integer::operator ++()
{
++n_;
return *this;
}
Integer Integer::operator++(int n)
{
Integer tmp(n_);
n_++;
return tmp;
}
void Integer::Display() const
{
cout<<n_<<endl;
}
#include "Integer.h"
#include <iostream>
using namespace std;
int main(void)
{
Integer n(100);
n.Display();
Integer n2 = ++n;
n.Display();
n2.Display();
Integer n3 = n++;
n.Display();
n3.Display();
return 0;
}
#ifndef _STRING_H_
#define _STRING_H_
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_;
};
#endif
#pragma warning(disable:4996)
#include "String.h"
#include <string.h>
#include <iostream>
using namespace std;
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;
}
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;
}
#include "String.h"
#include <iostream>
using namespace std;
int main(void)
{
String s1("abc");
String s2(s1);
String s3;
s3 = s1;
s3.Display();
s3 = "xxxx";
s3.Display();
return 0;
}