Академический Документы
Профессиональный Документы
Культура Документы
this pointer:
- Implicit parameter passed to a member
function
- points to the object calling the function
11-2
USING THE THIS POINTER
11-6
EXAMPLE
11-8
EXAMPLE
class Distance //English Distance class
{
private:
int feet; float inches;
public: //2-arg constructor
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //user input non-const func
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
} 11-9
void showdist() const //display distance const func
{
cout << feet << “\’-” << inches << ‘\”’; }
};
////////////////////////////////////////////////////////////////
int main()
{
const Distance football(300, 0);
football.getdist(); //ERROR: getdist() not const
cout << “football = “;
football.showdist(); //OK
cout << endl;
return 0;
11-10
}
11.2 STATIC MEMBERS
Static member variable:
One instance of variable for the entire class
Shared by all objects of the class
11-11
STATIC MEMBER VARIABLES
1) Must be declared in class with keyword static:
class IntVal
{
private:
int value;
static int valCount;
public:
intVal(int val = 0)
{ value = val; valCount++ }
int getVal();
void setVal(int);
};
11-12
STATIC MEMBER VARIABLES
2) Must be defined outside of the class:
class IntVal
{
//In-class declaration
static int valCount;
};
//Definition outside of class
int IntVal::valCount = 0;
11-13
STATIC MEMBER VARIABLES
valCount
val1 2 val2
11-14
STATIC MEMBER FUNCTIONS
11-17