Konštantné členské funkcie sú funkcie, ktorým je odmietnuté povolenie na zmenu hodnôt údajových členov ich triedy. Aby bola členská funkcia konštantná, kľúčové slovo const sa pripojí k prototypu funkcie a tiež k hlavičke definície funkcie.
Podobne ako členské funkcie a argumenty členských funkcií, aj objekty triedy môžu byť deklarované ako const. Objekt deklarovaný ako const nemožno modifikovať, a preto môže vyvolať iba členské funkcie const, pretože tieto funkcie zaistia, že objekt neupravia. Objekt const možno vytvoriť pridaním kľúčového slova const pred deklaráciu objektu. Akýkoľvek pokus o zmenu údajového člena objektov const má za následok chybu v čase kompilácie.
Syntax
Členská funkcia const môže byť definovaná tromi spôsobmi:
1. Pre deklaráciu funkcie v rámci triedy.
return_type function_name () const ;>
Príklad:
int get_data() const;>
2. Pre definíciu funkcie v rámci deklarácie triedy.
return_type function_name () const { //function body }> Príklad:
int get_data() const { //function body }> 3. Pre definíciu funkcie mimo triedy.
return_type class_name::function_name () const { //function body }> Príklad:
int Demo :: get_data() const { }> Dôležité body
- Keď je funkcia deklarovaná ako const, možno ju volať na akýkoľvek typ objektu, na objekt const, ako aj na non-const objekty.
- Vždy, keď je objekt deklarovaný ako const, je potrebné ho inicializovať v čase deklarácie. inicializácia objektu pri deklarácii je však možná len pomocou konštruktorov.
- Funkcia sa stane const, keď sa v deklarácii funkcie použije kľúčové slovo const. Myšlienkou const funkcií je neumožniť im modifikovať objekt, na ktorom sú volané.
- Odporúča sa vytvoriť čo najviac funkcií, aby sa predišlo náhodným zmenám objektov.
Príklady funkcií členov Const
Príklad 1
Nižšie uvedený program C++ ukazuje, že dátové členy možno aktualizovať v členskej funkcii, ktorá nie je konštantná.
C++
// C++ program to demonstrate that data members can be> // updated in a member function that is not constant.> #include> using> namespace> std;> class> Demo {> >int> x;> public>:> >void> set_data(>int> a) { x = a; }> >// non const member function> >// data can be updated> >int> get_data()> >{> >++x;> >return> x;> >}> };> main()> {> >Demo d;> >d.set_data(10);> >cout << d.get_data();> >return> 0;> }> |
>
>Výkon
11>
Príklad 2
Nižšie uvedený program C++ ukazuje, že údaje nemožno aktualizovať v členskej funkcii Constant.
ostrý uhol
C++
// C++ program to demonstrate that data cannot be updated> // in a Constant member function> #include> using> namespace> std;> class> Demo {> >int> x;> public>:> >void> set_data(>int> a) { x = a; }> >// constant member function> >int> get_data()>const> >{> >// Error while attempting to modify the data> >// member> >++x;> >return> x;> >}> };> main()> {> >Demo d;> >d.set_data(10);> >cout << endl << d.get_data();> >return> 0;> }> |
>
>
Výkon
./Solution.cpp: In member function 'int Demo::get_data() const': ./Solution.cpp:17:11: error: increment of member 'Demo::x' in read-only object ++x; ^>
Príklad 3
Nižšie uvedený kód C++ ukazuje, ako definovať konštantné členské funkcie mimo definície triedy, a ukazuje použitie konštantnej členskej funkcie na nastavenie a získanie hodnoty súkromnej členskej premennej.
C++
// Constant member function defined outside the class> #include> using> namespace> std;> class> Demo {> >int> x;> public>:> >void> set_data(>int>);> >// const member function> >int> get_data()>const>;> };> // Function definition for setting the value of x.> void> Demo::set_data(>int> a) { x = a; }> // Function definition for retrieving the value of x (const> // member function).> int> Demo::get_data()>const> {>return> x; }> main()> {> >Demo d;> >// Set the value of x to 10 using the non-const member> >// function.> >d.set_data(10);> >// Print the value of x using the const member function.> >cout << d.get_data();> >return> 0;> }> |
>
>Výkon
10>
Príklad 4
Nižšie uvedený program C++ demonštruje, že funkcie const môžu byť volané inými ako const objektmi.
C++
rhel vs centos
// C++ program to demonstrate that const functions can be> // called by non const objects> #include> using> namespace> std;> class> Test {> >int> value;> public>:> >Test(>int> v = 0) { value = v; }> >// const member function> >int> getValue()>const> {>return> value; }> };> int> main()> {> >// non const object> >Test t(20);> >cout << t.getValue();> >return> 0;> }> |
>
>Výkon
20>
Keď je funkcia deklarovaná ako const, možno ju volať na akýkoľvek typ objektu. Non-const funkcie môžu byť volané iba non-const objektmi.
Napríklad nasledujúci program má chyby kompilátora.
C++
// C++ program that demonstrate that non-const functions can> // not be called by const objects> #include> using> namespace> std;> class> Test {> >int> value;> public>:> >Test(>int> v = 0) { value = v; }> >// non const member function> >int> getValue() {>return> value; }> };> int> main()> {> >// const object> >const> Test t;> >cout << t.getValue();> >return> 0;> }> |
>
>
Výkon
./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp: In function 'int main()': ./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp:14:24: error: passing 'const Test' as 'this' argument of 'int Test::getValue()' discards qualifiers [-fpermissive] cout << t.getValue();>
Pozrime sa na ďalší príklad:
C++
vkladací python
// Demonstration of constant object,> // show that constant object can only> // call const member function> #include> using> namespace> std;> class> Demo {> >int> value;> public>:> >Demo(>int> v = 0) { value = v; }> >void> showMessage()> >{> >cout <<>'Hello World We are Tushar, '> >'Ramswarup, Nilesh and Subhash Inside'> >' showMessage() Function'> ><< endl;> >}> >// const member function> >void> display()>const> >{> >cout <<>'Hello world I'm Rancho '> >'Baba Inside display() Function'> ><< endl;> >}> };> int> main()> {> >// Constant object are initialised at the time of> >// declaration using constructor> >const> Demo d1;> >// d1.showMessage();Error occurred if uncomment.> >d1.display();> >return> (0);> }> |
>
>Výkon
Hello world I'm Rancho Baba Inside display() Function>
Časté otázky o funkciách členov Const
Q1. Môžu const objekty triedy volať nekonštantné členské funkcie?
odpoveď:
Nie, objekt deklarovaný ako const nemožno modifikovať, a preto môže vyvolať iba členské funkcie const, pretože tieto funkcie zaručujú, že objekt neupravia.
Q2. Môžu non-const objekty triedy volať const členskú funkciu?
odpoveď:
Keď je funkcia deklarovaná ako const, možno ju volať na akýkoľvek typ objektu.