Created
January 7, 2023 00:55
-
-
Save EteimZ/7312560478a20fc9aa584b66cc42e55c to your computer and use it in GitHub Desktop.
Counter example from the book C how to program.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Implementation file for Count class | |
| #include <iostream> | |
| #include "Count.h" | |
| using std::cout; | |
| using std::endl; | |
| // set value of private data member x | |
| void Count::setX(int value){ | |
| x = value; | |
| } | |
| // print value of private data member x | |
| void Count::print(){ | |
| cout << x << endl; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Definition file for Count class | |
| // class Count definition | |
| #ifndef COUNT_H | |
| #define COUNT_H | |
| class Count{ | |
| public: | |
| void setX(int); | |
| void print(); | |
| private: | |
| int x; | |
| }; | |
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using std::cout; | |
| using std::endl; | |
| #include "Count.h" | |
| int main(){ | |
| Count counter; // create counter object | |
| Count *counterPtr = &counter; // create a pointer to counter | |
| Count &counterRef = counter; // create a reference to counter | |
| cout << "Set x to 1 and print using the object's name: "; | |
| counter.setX( 1 ); // set data member x to 1 | |
| counter.print(); // call member function print | |
| cout << "Set x to 2 and print using a reference to that object: "; | |
| counterRef.setX( 2 ); // set data member x to 1 | |
| counterRef.print(); // call member function print | |
| cout << "Set x to 3 and print using a pointer to that object: "; | |
| counterPtr->setX( 3 ); // set data member x to 1 | |
| counterPtr->print(); // call member function print | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment