Sunteți pe pagina 1din 3

Constant Member Functions

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant.

// constant_member_function.cpp class Date { public: Date( int mn, int dy, int yr ); int getMonth() const; void setMonth( int mn ); private: int month; }; // A read-only function // A write function; can't be const

int Date::getMonth() const { return month; } void Date::setMonth( int mn ) { month = mn; } int main() { Date MyDate( 7, 4, 1998 ); const Date BirthDate( 1, 18, 1953 ); MyDate.setMonth( 4 ); BirthDate.getMonth(); // Okay // Okay // Modifies data member // Doesn't modify anything

BirthDate.setMonth( 4 ); // C2662 Error }

Static
Grammar storage-class-specifier:static

When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared). A variable declared static in a function retains its state between calls to that function. When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members. Static data members of classes must be initialized at file scope. In recursive code, a static object or variable is guaranteed to have the same state in different instances of a block of code. The members of a union cannot be declared as static. An anonymous union declared globally must be explicitly declared static. Objects and variables defined outside all blocks have static lifetime and external linkage by default. A global object or variable that is explicitly declared as static has internal linkage.

static1.cpp // compile with: /EHsc #include <iostream>

using namespace std; void showstat( int curr ) { static int nStatic; // Value of nStatic is retained // between each function call nStatic += curr; cout << "nStatic is " << nStatic << endl; }

int main() { for ( int i = 0; i < 5; i++ ) showstat( i ); }


Output

nStatic is 0 nStatic is 1 nStatic is 3 nStatic is 6 nStatic is 10

S-ar putea să vă placă și