类的访问控制技巧
来源:互联网 发布:mac版ico转换器 编辑:程序博客网 时间:2024/06/08 11:05
1,代理指针,保证对象的释放
// ProxyPtr.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
private:
double m_f64Real;
double m_f64Image;
public:
Complex(double f64Real = 0.0, double f64Image = 0.0)
{
cout << "in Complex" << endl;
m_f64Real = f64Real;
m_f64Image = f64Image;
}
virtual ~Complex()
{
cout << "in ~Complex" << endl;
}
void Display()
{
cout << "(" << m_f64Real << ", " << m_f64Image << ")" << endl;
}
};
class ComplexPtr
{
private:
Complex* m_poComplex;
public:
explicit ComplexPtr(Complex* poComplex) : m_poComplex(poComplex)
{
cout << "in ComplexPtr" << endl;
}
virtual ~ComplexPtr() // 退栈时自动调用析构函数
{
cout << "in ~ComplexPtr" << endl;
if (m_poComplex)
{
delete m_poComplex;
m_poComplex = NULL;
}
}
Complex* operator ->()
{
return m_poComplex;
}
Complex& operator *()
{
return *m_poComplex;
}
private:
ComplexPtr(const ComplexPtr&);
ComplexPtr& operator =(const ComplexPtr&);
void* operator new(size_t); // 声明为私有的,使得不能在堆上分配ComplexPtr类型的对象
//void operator delete(void*);
void* operator new[](size_t); // 声明为私有的,使得不能在堆上分配ComplexPtr类型的对象
//void operator delete[](void*);
};
int main()
{
ComplexPtr oComplexPtr(new Complex(10, 10));
oComplexPtr->Display();
(*oComplexPtr).Display();
//ComplexPtr* poComplexPtr = new ComplexPtr(new Complex(20, 20)); // 编译出错,因为new声明为私有的了
return 0;
}
2,非公有的构造函数,使得在类域之外无论是在栈上还是在堆上均不能创建对象
// NonePublicConstructor.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Test
{
protected: // 非公有的构造函数,使得在类域之外无论是在栈上还是在堆上均不能创建对象
Test()
{
cout << "in Test" << endl;
}
public:
virtual ~Test()
{
cout << "in ~Test" << endl;
}
static Test* CreateInstance() // 相当于一个工厂方法,也可使用单件那样的方式,在类中保存一个对象
{
return new Test(); // 在类域之类,可以访问非公有的构造函数
}
};
int main()
{
//Test t; // 编译报错
//Test* pt = new Test(); // 编译报错
Test* pt = Test::CreateInstance();
delete pt;
return 0;
}
3,非公有的析构函数,使得在不能在栈上创建对象,因为退栈时会自动调用析构函数,即只能在堆上创建对象
// NonePublicDestructor.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "in Test" << endl;
}
void Release()
{
cout << "in Release" << endl;
delete this; // 此处自动调用析构函数,因为是在类域中调用,所以可以访问私有的析构函数
}
private: // 私有的析构函数,使得在不能在栈上创建对象,因为退栈时会自动调用析构函数,即只能在堆上创建对象
~Test()
{
cout << "in ~Test" << endl;
}
};
int main()
{
//Test t; // 编译报错
Test* pt = new Test();
pt->Release();
return 0;
}
4,只能在栈上创建,不能在堆上创建:
将new和delete重载为私有的。
- 类的访问控制技巧
- 类的访问控制
- 类的访问控制
- JAVA类的访问控制
- PHP类的访问控制
- 类成员的访问控制
- 派生类的访问控制
- C++类的访问控制
- 类的访问控制符
- 类成员的访问控制
- 类成员的访问控制
- JAVA-类的访问控制
- 类边界(java的访问控制)
- 类的访问控制权限讨论
- JAVA类成员的访问控制
- 类中成员的访问控制
- 类成员的访问控制(C++)
- C++类成员的访问控制
- cocos2d-x 如何使用Visual Studio 2010和xcode 4混合编写手机游戏
- 机器视觉领域的牛人们的博客
- Visulal C++是什么?——兼谈其他
- swt中的SashForm
- 百度Android开发面试题
- 类的访问控制技巧
- ubuntu software
- 一步一步写算法(之“数星星”)
- JMVM,JMVC
- Hash函数以及解决冲突的方法
- spring aop 小结
- 源代码阅读工具:Vim+Taglist+Ctags
- Ext2那些事儿(三)
- Extjs+jquery实现动态载入多个页面,实现iframe效果