今天七夕,群友让我帮忙给他分配一个对象,于是我只好尝试给他分配对象了:
CGirlFrined *pGF = new CGirlFrined("大屌萌妹");int nRet = (群友).SetGirlFriend(pGF);if (nRet != 0)
{alert("分配失败!");
}
后来觉得这段代码过于简单,分配的方法也有些过于简单了,于是我参考了网上的代码,然后丰富了代码内容,包含NTR在内的更多的分配方式:
#include <iostream>
#include <list>using namespace std;class CGirlFriend {
public:string name;int age;CGirlFriend() {this->name = "小萝莉";this->age = 0;}CGirlFriend(const string& name, int age = 12): name(name), age(age){}static void* operator new(size_t size){ cout << "女朋友准备中。。。" << endl;return malloc(size);}static void* operator new(size_t size, CGirlFriend* ptr){ cout << "NTR别人的女朋友。。。" << endl;return ptr;}static void* operator new[](size_t size) { cout << "一大波女朋友准备中。。。" << endl;return malloc(size);}static void* operator new[](size_t size, list<void*>& lt) { cout << "女朋友们的聚会准备中。。。" << endl;void* tmp = malloc(size);lt.push_back(tmp);return tmp;}
};int main(void)
{CGirlFriend* gf1 = new CGirlFriend("小萝莉");CGirlFriend* gf2 = new(gf1) CGirlFriend;delete gf2;CGirlFriend* gfs = new CGirlFriend[10]{ { "萌妹子", 19 } };for (int i = 0; i < 10; ++i)cout << (gfs + i)->name.c_str() << endl;delete[] gfs;list<void*> girlList;CGirlFriend* gfss1 = new (girlList) CGirlFriend[10];for (int i = 0; i < 10; ++i)cout << (gfss1 + i)->name.c_str() << endl;CGirlFriend* gfss2 = new (girlList) CGirlFriend[20];for (auto& ptr : girlList)delete[] ptr;system("pause");return 0;}
此代码在vs2015上测试运行通过,结果如下:
欢迎交流与讨论。