一。malloc与free 和 new与delete有什么区别
#include <cstdlib> #include <iostream> using namespace std; class Test { public: Test(int i) { cout <<"Test(int i)"<< endl; this->i = i; } Test() { cout <<"Test()" << endl; } ~Test() { cout <<"~~Test" <<endl; } int getI() { return i; } private: int i; }; void func() { int* p = reinterpret_cast<int*>(malloc(sizeof(int))); int* q = new int(10); *p = 5; // *q = 10; cout<< *p << " " << *q << endl; free(p); delete q; Test* op = reinterpret_cast<Test*>(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 <cstdlib> #include <iostream> 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 <cstdlib> #include <iostream> 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)"<<endl; for(int i=1; i<=10; i++) { cout<<fib1(i)<<endl; } cout<<endl; cout<<"int fib2()"<<endl; for(int i=1; i<=10; i++) { cout<<fib2()<<endl; } cout<<endl; Fib fib; cout<<"Fib fib;"<<endl; for(int i=1; i<=10; i++) { cout<<fib()<<endl; } cout<<endl; cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS; }
两中实现的问题:
1.fib1是以无状态函数的方式实现的,求解数列的每一项都会做重复的循环,时间的复杂度为0(n)
2.fib2是以状态函数的方式实现的,每调用一次就可以得到数列当前项的值,时间复杂度为0(1),但是无法从头再来