函数操作符() 仿函数
把类对象当成函数名一样使用,需要重载()
class Pow
{
public:
int operator()(int i)
{
return i*i;
}
}
//power.operator()(i)-> power()i->power(i)使得类对象和函数更相似一些
//仿函数
仿函数主要应用于STL和模板
#include <iostream>
#include <vector>
#include <algorithm>
bool myCmp(int i, int j)
{
return i<j;
}
class Cmp
{
public:
bool operator()(int i, int j)
{
return i<j;
}
}
int main
{
int array[8] = {5, 3, 2, 12, 334, 1, 90, 11};
vector<int> vi(array, array+8);
//sort(vi.begin(), vi.end(), myCmp); or
sort(vi.begin(), vi.end(), Cmp());
// 传类比传函数好,因为类可以放入新的变量,而传函数信息量过少
// lambda [=](int i, int j){return i<j;}; lambda本质就是仿函数
for (int i = 0; i < vi.size(); i++)
{
cout<<vi[i]<<endl;
}
}
new delete new[] delete[] 重载
堆内存操作符 new delete
void *operator new(size_t)
void operator delete(void *)
void *operator new[](size_t)
void operator delete[](void *)
适用于极个别情况需要定制的时候才会用到,一般很少用到。
class A
{
public
A()
{
cout<<"A()"<<endl;
}
~A()
{
cout<<"~A()"<<endl;
}
};
void *operator new(size_t)
{
//size_t平台自动设定的,便于以后版本更新
//unsigned int
cout<<"void *operator new(size_t)"<<endl;
}
void operator delete(void *)
{
out<<"void operator delete(void *)"<<endl;
}
int main()
{
A *pa = new A; // 拉起构造器的调用
delete pa; //拉起析构器的调用
A * pm = (A*)malloc(sizeof(A));//不会拉起构造器的调用
free(pm);
return 0;
}
// 定制化 我要实现A类对象的生成,用我自己定制的new,delete
// 而其它仍然使用系统的
智能指针
#include <memory>// C++里面的库
//#include <memory.h> //C语言里面的库
class A
{
public
A()
{
cout<<"A()"<<endl;
}
~A()
{
cout<<"~A()"<<endl;
}
void func()
{
cout<<"void A::func()"<<endl;
}
};
//void foo()
//{
// A a;
//}
//void foo()
//{
//A *p = new A;
//
//delete p;
//}
// new A被ptr托管后,不需要再关系delete的问题。 delete在ptr离开其栈空间的时候发生。
// 对象的行为表现像指针。
// 对象的行为表现像函数说明重载了()
// 对象的行为表现像指针说明重载了-> *
void foo()
{
auto_ptr<A> ptr(new A);//auto_ptr类模板 auto_prt<A>模板类
ptr->func();
(*ptr).func();
}
class Smt
{
public:
Smt(A* p)
{
ptr = p;
}
~Smt()
{
delete ptr;
}
A*& operator->()
{
return ptr;
}
A& operator*()
{
return *ptr;
}
private
A * ptr;
};
int main()
{
foo();
return 0;
}