++运算符的重载
前置++运算符的重载
- 成员函数的方式重载,原型为:函数类型 & operator++();
- 友元函数的方式重载,原型为:friend 函数类型 & operator++(类类型&);
后置++运算符的重载
- 成员函数的方式重载,原型为:函数类型 operator++(int 参数);
- 友元函数的方式重载,原型为:friend 函数类型 operator++(类类型&,int 参数);
//Integer.h
#ifndef _INTEGER_H_
#define _INTEGER_H_
class Integer
{
public:
Integer(int n);
~Integer();
void Display() const;
Integer& operator++(); //前置运算符重载
Integer operator++(int n); //后置运算符重载
//friend Integer& operator++(Integer& i); //前置运算符重载,友元方式
//friend Integer operator++(Integer& i,int n); //后置运算符重载,友元方式
private:
int n_;
};
#endif // _INTEGER_H_
//Integer.cpp
#include "Integer.h"
#include<iostream>
using namespace std;
Integer::Integer(int n):n_(n)
{
}
Integer::~Integer(void)
{
}
void Integer::Display() const
{
cout << n_ <<endl;
}
Integer& Integer::operator++()
{
++n_;
return *this;
}
Integer Integer::operator++(int n)
{
Integer tmp(n_);
tmp.n_ = n_;
++n_;
return tmp;
}
//!<友元函数与成员函数不可共存
//Integer& operator++(Integer& i)
//{
// ++i.n_;
// return i;
//}
//Integer operator++(Integer& i,int n)
//{
// Integer tmp(i.n_);
// ++i.n_;
// return tmp;
//}
赋值运算符的重载
!运算符的重载
函数类型 operator!() const
流运算符重载
- C++的I/O流库的一个重要特性就是能够支持新的数据类型的输出和输入;
- 用户可以通过对插入符(<<)和提取符(>>)进行重载来支持新的数据类型;
- 流运算符的重载只能使用友元函数进行重载
frinend istream& operator>>(istream&,类类型&)
frinend ostream& operator<<(ostream&,const 类类型&)
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char* str="");
friend ostream& operator<<(ostream& os,const MyString& str);
friend istream& operator>>(istream& is,MyString& str);
~MyString();
private:
char* str_;
};
ostream& operator<<(ostream& os,const MyString& str)
{
os<<str.str_;
return os;
}
istream& operator>>(istream& is,MyString& str)
{
char tmp[1024];
cin>>tmp;
str = tmp;
return is;
}
类型转换运算符的重载
- 必须是成员函数,不能是友元函数
- 不能指定返回类型(其实已经指定了)
- 没有参数(操作数是什么?)不能指定返回类型(其实已经指定了)
函数原型:operator 类型名();
class Integer
{
public:
Integer(int n);
~Integer();
operator int(); //没有返回类型,其实返回类型已经为int;也没有参数,因为参数就是自己本身
private:
int n_;
};
Integer::operator int()
{
return n_;
}
int main(void)
{
Integer a(100);
int x = a; //
int y = static_cast<int>(a);// 二者调用的都是类型转换运算符
return 0;
}
->运算符
operator new、operator delete
new的三种语法:
- operator new
- new operator
- placement new
int main(void)
{
Test* p1 = new Test(100); //new operator = operator + 构造函数的调用
char chunk[10];
Test* p2 = new (chunk) Test(200); //在chunk的内存上分配内存
//placement new
}
具体情况:
- void* operator new(size_t size)
- void operator delete(void* p)
- void operator delete(void* p, size_t size)
- void* operator new(size_t size, const char* file, long line)
- void operator delete(void* p, const char* file, long line)
- void* operator new[](size_t size)
- void operator delete[](void* p)
- void operator delete[](void* p, size_t size)