一。malloc与free 和 new与delete有什么区别
#include#include using namespace std;class Test{ public: Test(int i) { cout <<"Test(int i)"<< endl; this->i = i; } Test() { cout <<"Test()" << endl; } ~Test() { cout <<"~~Test" < (malloc(sizeof(int))); int* q = new int(10); *p = 5; // *q = 10; cout<< *p << " " << *q << endl; free(p); delete q; Test* op = reinterpret_cast (malloc(sizeof(Test))); Test* oq = new Test; cout << op->getI() <<" "<< oq->getI()<< endl; free(op); delete oq;}int main(int argc, char *argv[]){ func(); cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS;}
1.malloc和free是库函数,以字节为单位申请堆内存
2.new和delete是关键字,以类型为单位申请堆内存。
3.malloc和free单纯的对内存进行申请和释放
4.对于基本类型new关键字会对内存进行初始化
5.对于类类型new和delete还负责构造函数和析构函数的调用
二。剥夺编译器对构造函数的调用尝试
c++提供了explicit关键字用于阻止编译器对构造函数的调用
explicit Test(int i) { cout <<"Test(int i)"<< endl; this->i = i; }
三。类的静态成员函数用来干嘛
单例模式
#include#include using namespace std;class Singleton{ private: static Singleton* cInstance; Singleton() { } public: static Singleton* GetInstance() { if(cInstance == NULL) { cInstance = new Singleton(); } return cInstance; } void print() { cout << "I'm Singleton" << endl; }};Singleton* Singleton::cInstance = NULL; void func(){ Singleton* s = Singleton::GetInstance(); s -> print();}int main(int argc, char *argv[]){ func(); cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS;}
四。无状态函数
函数的调用结果只与实参值相关
状态函数
函数的调用结果不仅与实参值相关还与之前的函数调用有关
#include#include using namespace std;int fib1(int i){ int a1 = 0; int a2 = 1; int ret = a2; while( i > 1) { ret = a2 + a1; a1 = a2; a2 = ret; i--; } return ret;}int fib2(){ static int a1 = 0; static int a2 = 1; int ret = a2; int t = a2; a2 = a2 + a1; a1 = t; return ret;}class Fib{private: int a1; int a2;public: Fib() { a1 = 0; a2 = 1; } int operator() () { int ret = a2; int t = a2; a2 = a2 + a1; a1 = t; return ret; }};int main(int argc, char *argv[]){ cout<<"int fib1(int i)"<
两中实现的问题:
1.fib1是以无状态函数的方式实现的,求解数列的每一项都会做重复的循环,时间的复杂度为0(n)
2.fib2是以状态函数的方式实现的,每调用一次就可以得到数列当前项的值,时间复杂度为0(1),但是无法从头再来