Konstantní členské funkce jsou funkce, kterým je odepřeno oprávnění měnit hodnoty datových členů jejich třídy. Aby byla členská funkce konstantní, je klíčové slovo const připojeno k prototypu funkce a také k hlavičce definice funkce.
Stejně jako členské funkce a argumenty členských funkcí mohou být objekty třídy také deklarovány jako const. Objekt deklarovaný jako const nelze upravit, a proto může vyvolat pouze členské funkce const, protože tyto funkce zajišťují, že objekt nezmění. Objekt const lze vytvořit přidáním klíčového slova const před deklaraci objektu. Jakýkoli pokus o změnu datového členu objektů const má za následek chybu při kompilaci.
Syntax
Členskou funkci const lze definovat třemi způsoby:
1. Pro deklaraci funkce v rámci třídy.
return_type function_name () const ;>
Příklad:
int get_data() const;>
2. Pro definici funkce v rámci deklarace třídy.
return_type function_name () const { //function body }>
Příklad:
int get_data() const { //function body }>
3. Pro definici funkce mimo třídu.
return_type class_name::function_name () const { //function body }>
Příklad:
int Demo :: get_data() const { }>
Důležité body
- Když je funkce deklarována jako const, lze ji volat na jakýkoli typ objektu, objekt const i non-const objekty.
- Kdykoli je objekt deklarován jako const, musí být inicializován v době deklarace. inicializace objektu při deklaraci je však možná pouze pomocí konstruktorů.
- Funkce se stane const, když se v deklaraci funkce použije klíčové slovo const. Myšlenka funkcí const je nedovolit jim upravovat objekt, na kterém jsou volány.
- Doporučuje se vytvořit co nejvíce funkcí konstantních, aby se zabránilo náhodným změnám objektů.
Příklady funkcí členů Const
Příklad 1
Níže uvedený program C++ ukazuje, že datové členy lze aktualizovat v členské funkci, která není konstantní.
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ýstup
11>
Příklad 2
Níže uvedený program C++ ukazuje, že data nelze aktualizovat v členské funkci Constant.
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ýstup
./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; ^>
Příklad 3
Níže uvedený kód C++ ukazuje, jak definovat konstantní členské funkce mimo definici třídy, a ukazuje použití konstantní členské funkce k nastavení a načtení hodnoty soukromé proměnné člena.
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ýstup
10>
Příklad 4
Níže uvedený program C++ ukazuje, že funkce const mohou být volány jinými objekty než const.
C++
// 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ýstup
20>
Když je funkce deklarována jako const, lze ji volat na jakýkoli typ objektu. Non-const funkce mohou být volány pouze non-const objekty.
Například následující program obsahuje chyby kompilátoru.
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ýstup
./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();>
Podívejme se na další příklad:
r v jazyce c
C++
// 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ýstup
Hello world I'm Rancho Baba Inside display() Function>
Časté otázky o funkcích členů Const
Q1. Mohou const objekty třídy volat jiné než const členské funkce?
Odpovědět:
Ne, objekt deklarovaný jako const nelze upravit, a proto může vyvolat pouze členské funkce const, protože tyto funkce zajišťují, že objekt nezmění.
Q2. Mohou non-const objekty třídy volat const členskou funkci?
Odpovědět:
Když je funkce deklarována jako const, lze ji volat na jakýkoli typ objektu.