C++: try to use const

const object, the function variable modification check will be enabled during operation, and the variable value cannot be modified in the called function. This check operation will be performed in each call of the function, but the member function limited by the const keyword is used. Only one variable modification check is performed during multiple function calls.

The const-modified function cannot modify the member variables of the class, but when the member variables are returned by the const member function, they can be modified.

Class String{
Public:
	Char* text;
	Bool valid; //Modify to mutable bool valid;
	Int length;
	Int GetLength() const
	{}
	Void DeleteChar(int pos)
	{}
	Bool CheckLength() const
	{
		If(length >= 1)
		valid = true;
	else
		valid = false;
	return;
}
};

cosnt String a(“hello world”);

a.GetLength(); //
a.DeleteChar(3) //Error call, the function will modify member variables

String b(“hello world”);
cout<<b.CheckLength()<<endl; //Error calling CheckLength() changes member variables,
		//Effective solution, add the mutable keyword before the variable valid declaration.
When the const version of '[]' (subscript reference operator) and the non-const version of '[]' (subscript reference operator) are both overloaded in the object. The practice of code reuse is to call the const version in the non-const version, and then use const_cast to remove the constant attribute of the return value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325563047&siteId=291194637