Chinaunix首页 | 论坛 | 博客
  • 博客访问: 894871
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: C/C++

2014-03-27 18:10:23

问题一:

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无效
#include 
using 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此时只是在说明有这么个类型,而并没有定义一个具体的变量和分配内存空间




阅读(2470) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~