C ++ notes ---- about common class member functions ----
Common member functions of classes in C ++
Declared style: return type <Class Identifier:> function name (parameter table) const
Notes:
1. const is part of the function declaration, and must be added to the implementation of the function.
2. the const keyword can be used to reload functions with the same function name but without the const keyword
3. A common member function cannot be used to update the member variables of a class, nor call a member function without const modification in the class. It can only call a common member function. That is, regular member functions cannot change the Member States in the class, which is consistent with the const semantics.
Example 1: const can overload functions, and const needs to be added to the implementation part.
#include <iostream>using namespace std;class TestA{public: TestA(){} void hello() const; void hello();};void TestA::hello() const{ cout << "hello,const!" << endl;}void TestA::hello(){ cout << "hello!" << endl;}int main(){ TestA testA; testA.hello(); const TestA c_testA; c_testA.hello();}
Running result:
Example 2: An example shows that a common member function cannot change the class variables or call a non-member function, but can call a common member function. A very member function can call a common member function.
# Include <iostream> using namespace std; class TestA {public: TestA () {} TestA (int a, int B) {this-> a =; this-> B = B;} int sum () const; int sum (); void helloworld () const; void hello (); private: int a, B ;}; int TestA: sum () const {// this-> a = this-> a + 10; // modified the class variable, an error 1 // this-> B = this-> B + 10 will be reported during compilation; // same as above // hello (); // a non-member function is called, compilation times Error 2 return a + B;} int TestA: sum () {this-> a = this-> a + 10; this-> B = this-> B + 10;
Helloworld (); // call the common member function return a + B;} void TestA: helloworld () const {cout <"hello, const" <endl ;} void TestA: hello () {cout <"hello" <endl ;}int main () {TestA testA; testA. sum (); const TestA c_testA; c_testA.sum ();}
When the annotation is removed, compilation reports Error 1, indicating that the class variables cannot be modified by the common member functions of the class.
Error 2 is as follows, indicating that a common member function cannot call a non-member function.