const keyword feature analysis (to be added)

Source: Internet
Author: User

const keyword

/***********************c++ Const characteristic Analysis *********************/
#include <iostream>

using namespace std;

Class a{
private:
	int A;
Public:
	A () {}
	a (int A) {a::a = A;}
	void SetA (const int& a) {
		a::a = A;
	}
	The const plus at the end indicates that the member function does not change the member variable in the class
	int geta () const{return
		A;
	}
	The return value is the const
	const a&
	operator= (const a& A0) {
		A = a0.a;
		return *this;
	}
;


int main () {
	//1. The value that the pointer points to cannot be changed
	const int* a1 = new int (1);
	cout << "*A1:" << *a1 << Endl;

	2. The value of the pointer itself cannot be changed
	int* const A2 = new int (2);
	cout << "*A2:" << *a2 << Endl;

	2. The value that the pointer points to can change
	*A2 =;
	cout << "*A2:" << *a2 << Endl;

	A A1;
	A A2;
	A A3;
	A1. SetA (3);
	If written (A2 = A3) = A1 will cause an error because the return value of the overloaded equal sign is const
	A2 = A3 = A1;
	cout << "A2. Geta (): "<< A2. Geta ();

	return 0;
}


Output:



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.