C++小知识

如何定义一个只能在(堆/栈)上生成对象的类

只能栈上生成的思路就是 重载 new/delete,限制不让外部访问

只能堆上生成的思路就是 限制外部访问析构函数,这样编译器检测到的话会对栈上的临时对象报错。

详见以下代码:



#include "stdafx.h"
#include 


// 只能在堆上创建对象的类
class A {
public:
	A() {
		std::cout << "A created" << std::endl;
	}
	void Print() {
		std::cout << "A Print" << std::endl;
	}
	virtual void Destroy() {
		std::cout << "A Destroy()" << std::endl;
		delete this;
	}
protected: //类允许被继承
	virtual ~A() {
		std::cout << "A destroyed" << std::endl;
	}
};

class C : public A {
public:
	C() {
		std::cout << "C created" << std::endl;
	}
	virtual ~C() {
		std::cout << "C destroyed" << std::endl;
	}
	virtual void Destroy() {
		std::cout << "C Destroy()" << std::endl;
		delete this;
	}
};

// 只能在栈上创建对象的类
class B {
private:
	void * operator  new (size_t  t){}     
	void  operator  delete (void * ptr){}
public:
	void Print() {
		std::cout << "B Print" << std::endl;
	}
};


int _tmain(int argc, _TCHAR* argv[])
{
	// A a;
	A* pa = new C;
	pa->Print();
	pa->Destroy();
	//delete pa;
	B b;
	b.Print();
	//B* pb = new B;
	//pb->Print();
	getchar();
	return 0;
}

static用法

C++虚函数表

你可能感兴趣的:(C++,c++,开发语言,算法)