I have some problems with my homework
Consider the following definition of the class myClass
<class myClass
{
private:
int x;
static int count;
public:
void setX(int a);
//Function to set the value of x.
//Postcondition: x = a;
void printX() const;
//Function to output x.
static void printCount();
//Function to output count.
static void incrementCount();
//Function to increment count.
//Postcondition: count++;
myClass(int a = 0);
//constructor with default parameters
//Postcondition x = a;
//If no value is specified for a, x = 0;
};>
Question 1: Write a C++ statement that initializes the member variable count to 0.
Question 2: Write a C++ statement that increments the value of count by 1.
Question 3: Write a C++ statement that outputs the value of count.
My answers are:
Question 1: int myClass::count =0;
Question 2: myClass::incrementCount();
Question 3: myClass::printCount();
However, all of the above answers are wrong, correct answers are:
Question 1: myClass::count=0;
Question 2: myClass.incrementCount();
Question 3: myClass::printCount();
In next exercise: Which of the following statements are valid?
myClass.printCount(); // statement 1
myClass.printX(); // statement 2
The answers are both statement are invalid.
Statement 1 in this exercise is invalid, however, in question 1 , it's valid
From what I learn, to access static member, I have to use "::" instead of "."
Right now I am super confused
struct A { staticint i ; staticint foo() { return i ; } };
int A::i = 7 ;
int main()
{
// access static members with class_name::
A::i = 7 ;
int x = A::foo() ;
// access static members with object.
A a ;
a.i = 8 ;
x = a.foo() ;
return A::i - a.i ;
}