c++ method const, return type const 7 minutes, maybe 5 minutes
const qualifier makes the object immutable. (Read day-10)
A const qualifier is placed after the method name and a pair of (), it will make the object immutable inside the scope of the current method.
class my_class { public: void fz_kp() const // Method const { } void kp_fz() { } };
The above const qualifer makes the current object immutable inside of the method .fz_kp(),
it can not make the object immutable outside of the method .fz_kp(), such as .kp_fz() .
To quickly understand it, the method const qualifier make the "*this" const .
Don't be confused by return type const and method const, the return type const qualifier is paced before the method_name() .
class my_class { public: const int kf_pz() // Return type const: The value it returned is const. { return 5; } };
I name method that is qualified by method const as const method now.
why?
This is an unofficial understanding:
You can insert immutable things into mutable things, but you can not insert mutable things into immutable things.
class my_class { public: void f_a() const {} void f_b() {} void f_c() const { f_a(); // OK //f_b(); // not allowed } void f_d() { f_a(); // OK f_b(); // OK } }; int main() { const auto obj = my_class{}; obj.f_a(); // OK //obj.f_b(); // ERROR, not allowed auto obj2 = my_class{}; obj2.f_a(); // OK obj2.f_b(); // OK }
Written on Oct 31, 2024
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
=================================== # The c++ programming language. # # # # Join c++ Discord: yZcauUAUyC # # Deck # ===================================