C++の定数const基本用法

2024 ワード

#include <iostream>
using namespace std;

class Const {
	const int i;
	int j;
public:
	Const(int ci);
	void test();
	const int* constTest();
	int* constTest2() const;
};

Const::Const(int ci):i(ci) {
	j = 18;
};

void Const::test() {
	int i0 = i;
	cout << "i0 = " << i0 << endl;//   

	const int* i1;//    ,    
	i1 = &i0;
	//int* const i2;//        
	int* const i2 = &i0;//    ,     

	cout << "i1 = " << i1 << endl;//   
	cout << "i2 = " << i2 << endl;//   
	
	//i2++;//      
	*i2 = 1;//     
	
	cout << "i1 = " << i1 << endl;//   
	cout << "i2 = " << i2 << endl;//   
	
	cout << "*i1 = " << *i1 << endl;//1
	cout << "*i2 = " << *i2 << endl;//1

	i1++;//      
	//*i1 = 2;//     
	
	cout << "i1 = " << i1 << endl;//   (   )
	cout << "i2 = " << i2 << endl;//   
	
	*i2 = 5;

	cout << "*i1 = " << *i1 << endl;//   
	cout << "*i2 = " << *i2 << endl;//5
	
	cout << "++*i2 = " << ++*i2 << endl;//6
	cout << "*i2 = " << *i2 << endl;//6
}

/* const       ,      const */
const int* Const::constTest() {
	j++;
	return &j;
}

/* const       ,   const   */
int* Const::constTest2() const {
	//j++;//const            
	//int* j1 = j;//const         int*
	int j1 = j;
	j1++;
	return &j1;
}

int main() {
	Const c(3);
	c.test();

	const int* const p = c.constTest();
	cout << "*p = " << *p << endl;//19
	
	const int* p2  = c.constTest2();
	cout << "*p2 = " << *p2 << endl;//20

getchar();
};

私の機械の運行結果は以下の通りです.
i0 = 3 i1 = 001DF950 i2 = 001DF950 i1 = 001DF950 i2 = 001DF950 *i1 = 1 *i2 = 1 i1 = 001DF954 i2 = 001DF950 *i1 = -858993460 *i2 = 5++*i2 = 6 *i2 = 5 *p = 19 *p2 = 20