c++ 在栈上或堆上创建对象实例源码

c++ 在栈上或堆上创建对象实例源码

只在栈上创建对象,
需要重载new和delete运算符,并且
让这两个运算符成为私有的:
C/C++ code
#include <iostream>
using namespace std;
class A {
public:
A() { cout<<”构造A”<<endl; }
~A() { cout<<”析构A”<<endl; }

private:
void* operator new (size_t t);
void operator delete(void *ptr);
};
int main() { //A* a = new A; //这句去掉会报错 A a; return 0; }

只能在堆上创建对象,
需要把析构函数改成私有的,
然后自己写个函数代替析构函数

C/C++ code

#include <iostream>
using namespace std;
class A {
public:
A() { cout<<”dhjj”<<endl; }
void distory () const { delete this; }

private:
~A() { cout<<”this”; }
};

int main() { //A a; //去掉会报错 A* a=new A; a->distory(); return 0; } 本文链接地址: c++ 在栈上或堆上创建对象实例源码