问题一:
int *p1 = new int[10]; int *p2 = new int[10](); 有啥区别?
答:
我理解
int *p2 = new int[10](); 申请了空间
而且进行了初始化 int *p1 = new int[10]; 只申请空间
没有进行初始化 原因: 对于
些
我们
看
()往往表示
int
基本类型算初始化吧 理由:
测试输出两种
值
会发现p1
值未知
而p2清零了
问题二:
c++里星号后加引用 创建二元查找树中,BSTreeNode *&pCurrent,这个*&是什么意思?去掉&程序出错,为什么?
答:*&是指针的引用,void addBSTreeNode(BSTreeNode *&pCurrent, int value) 去掉&的话,相当于按值传递过来一个指针,函数对pCurrent的修改只在函数中起作用,对于原来的pCurrent无效
#includeusing namespace std; struct BSTreeNode { int node_value; BSTreeNode *pleft; BSTreeNode *pright; }; void AddBSTreeNode(BSTreeNode *&pcurrent, int value) { if(NULL == pcurrent) { BSTreeNode *pBSTree = new BSTreeNode(); pBSTree->pleft = NULL; pBSTree->pright = NULL; pBSTree->node_value = value; pcurrent = pBSTree; } else { if((pcurrent->node_value) > value) { AddBSTreeNode(pcurrent->pleft, value); } else if((pcurrent->node_value) < value) { AddBSTreeNode(pcurrent->pright, value); } else { cout << "重复输入节点:" << value << endl; } } } void TravelBSTree(BSTreeNode *pcurrent) { // cout << "Into the travel:" << endl; if(NULL == pcurrent) return; if(NULL != pcurrent->pleft) { TravelBSTree(pcurrent->pleft); } cout << pcurrent->node_value << endl; if(NULL != pcurrent->pright) { TravelBSTree(pcurrent->pright); } } int main() { BSTreeNode *proot = NULL; AddBSTreeNode(proot, 10); AddBSTreeNode(proot, 9); AddBSTreeNode(proot, 11); AddBSTreeNode(proot, 6); AddBSTreeNode(proot, 45); AddBSTreeNode(proot, 37); AddBSTreeNode(proot, 23); AddBSTreeNode(proot, 0); TravelBSTree(proot); return 0; }
1.分配内存,调用构造函数时,隐式/显示的初始化各数据成员 2.进入构造函数后在构造函数中执行一般计算 1.类里面的任何成员变量在定义时是不能初始化的。 2.一般的数据成员可以在构造函数中初始化。 3.const数据成员必须在构造函数的初始化列表中初始化。 4.static要在类的定义外面初始化。 5.数组成员是不能在初始化列表里初始化的。 6.不能给数组指定明显的初始化。 这6条一起,说明了一个问题:C++里面是不能定义常量数组的!因为3和5的矛盾。
记住静态成员这样初始化: C/C++ code class A { public: static const int a[3]; }; const int A::a[3] = {1,2,3};除了静态数据成员外,数据成员不能在类体内显式的初始化 举个最简单例子 struct a { int a=1; int b=2; }; 这也不能通过啊! 原因很简单,因为struct a此时只是在说明有这么个类型,而并没有定义一个具体的变量和分配内存空间