C++ Classes
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members.
// Syntax class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;
Working example:
// classes example #include <iostream> using namespace std; class Rectangle { int width, height; public: void set_values (int,int); int area() {return width*height;} }; void Rectangle::set_values (int x, int y) { width = x; height = y; } int main () { Rectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; }
The result is:
area: 12
For italian people: come funziona?
1. Viene per prima eseguita la funzione main ()
2. Rectangle rect; -> da qui quando scriverò rect farò riferimento a Rectangle
3. rect.set_values (3,4); -> è come se scrivessi Rectangle.set_values (3,4);
4. void Rectangle::set_values -> la classe Rectangle::funzione set_values riceve 3,4
5. quindi assegna alle variabili width = 3; height = 4;
6. tornando all’interno di main() -> rect.area(); -> la classe Rectangle, funzione area, ritorna width*height = 3*4 = 12