天天看點

const和*,**搭配的解釋const和*,**搭配的解釋

const和*,**搭配的解釋

  • 類型一:const 和 int
  • 類型二:const和 int 和 *
  • 類型三:const 和 int 和 **

注:以下舉例以int作為類型,且new的資料未作delete處理

類型一:const 和 int

//類型一
	const int i1 = 2;//【Ⅰ】
	// i1 = 3;//error

	int const i2 = 2;//【Ⅱ】等價于【Ⅰ】
	//i2 = 3;//error 
           

類型二:const和 int 和 *

int* tpi = new  int(1);
	int** tppi = new int* (new int(1));
	
	//類型二
	const int* pi_11{ new int(2) };//【Ⅲ】pi_11指向的值為常量
	//(*pi_11) = 3;//error
	pi_11 = tpi;//success

	int const* pi_12{ new int(2) };//【Ⅳ】等價于【Ⅲ】
	//(*pi_12) = 3;//error
	pi_12 = tpi;//success
	*tpi = 3;
	int* const pi_13{ new int(2) };//Ⅴ】pi_13指針為常量
	(*pi_13) = 3;//success
	//pi_13 = tpi;//error

	const int* const pi{ new int(2) };//【Ⅵ】pi指針為常量,且pi指向的值也為常量
	//pi = tpi;//error
	//(*pi) = 3;//error
           

類型三:const 和 int 和 **

int* tpi = new  int(1);
	int** tppi = new int* (new int(1));
    const int* pi_11{ new int(2) };
	//類型三
	int* const* const ppi1{ new int* (new int(2)) };//【Ⅶ】ppi1指針為常量,且ppi1指針的指針為常量
	//ppi1 = tppi;//error
	//(*ppi1) = tpi;//error
	(*(*ppi1)) = 3;//success

	const int* const* const ppi2{ new int* (new int(2)) };//【Ⅷ】ppi2指針為常量,且ppi2指針的指針為常量,且ppi2指針的指針指向的值也為常量
	//ppi2 = tppi;//error
	//(*ppi2) = tpi;//error
	//(*(*ppi2)) = 3;//error
	int const * const* const ppi3{ new int* (new int(2)) };//【Ⅸ】等價于【Ⅷ】

	int** const ppi4{ new int* (new int(2)) };//【Ⅹ】ppi5二級指針為常量
	//ppi4 = tppi;//error
	(*ppi4) = tpi;//success
	(*(*ppi4)) = 2;//sucess

	const int** ppi5{ new const int* (new int(2)) };//【ⅩⅠ】ppi5指針的指針指向的值為常量
	ppi5 = &pi_11;//success
	(*ppi5) = pi_11;//success
	//(*(*ppi5)) = 2;//error

	int const** ppi6{ new const int* (new int(2)) };//【ⅩⅡ】等價于【ⅩⅠ】
           
  • 我的GitHub
  • 我的CSDN
  • 我的Gitee

繼續閱讀