C++类是其语言很重要的一个特色,提供了丰富的功能。
类模拟指针(与智能指针的原理一样)
程序实例
//pointer like class
namespace tt4
{
template<typename T>
class shared_ptr
{
public:
shared_ptr(T* x)
:px(x)
{}
~shared_ptr()
{
if (px != nullptr)
{
delete px;
}
}
//提供*、->重载函数,这是作为指针变量的常用方法
T& operator*() const
{
return *px;
}
T* operator->() const
{
return px;
}
private:
//所谓智能指针,其实其内部保存了真正的指针
//由其自身来为我们进行创建和销毁
T* px;
};
}
int main()
{
//使用
tt4::shared_ptr<int> p(new int(5));
system("pause");
return 0;
}
说明
- 智能指针是使用类来表示指针。
- 容器中的迭代器也是使用类来表示的指针。
类模拟函数
#include <iostream>
#include <string>
namespace tt5
{
//使用类来模拟函数
class Hello
{
public:
int operator()(string msg) const
{
cout << "hello " << msg << endl;
return 0;
}
};
}
int main()
{
//使用
tt5::Hello h;
h("1111111");
system("pause");
return 0;
}