c++

C++ Classes

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

By |C++, Video Games Development|Commenti disabilitati su C++ Classes

C++ Enum

C++ Enum

Quando si definisce una variabile di tipo enumerativo, ad essa viene associato un insieme di costanti intere chiamato insieme dell’enumerazione. La variabile può contenere una qualsiasi delle costanti definite.

enum


// Sintassi
enum type_name {
  value1,
  value2,
  value3,
  .
  .
} object_names;


// 1. definiamo secchio come un tipo di dati enum
// all'interno indico il valore delle costanti
enum secchio {
    VUOTO,
    MEZZO_PIENO,
    PIENO = 5
} mio_secchio;

// 2. poi possiamo definire:
secchio tuo_secchio;
// oppure in modo equivalente
enum secchio tuo_secchio;

// 3. poi posso assegnare i valori delle costanti
// NON POSSO ASSEGNARE VALORI AL DI FUORI DELLE COSTANTI
mio_secchio = PIENO;
tuo_secchio = VUOTO;

Un’altro esempio:
creo un tipo di variabile colors_t dove immagazzinare i colori.

...
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};
...

enum class

Con ‘enum class’ possiamo dichiarare non solo interi, ma anche altri tipi di dato.

...
enum class EyeColor : char {blue, green, brown}; 
...

My Website: http://www.lucedigitale.com

Reference: http://www.cplusplus.com/doc/tutorial/other_data_types/
Reference: http://www.html.it/pag/15478/gli-identificatori/

By |C++, Video Games Development|Commenti disabilitati su C++ Enum

C++ Unions

C++ Unions

Unions allow one portion of memory to be accessed as different data types.

The code below creates a new union type, identified by type_name, in which all its member elements occupy the same physical space in memory. The size of this type is the one of the largest member element.


// Syntax
union type_name {
  member_type1 member_name1;
  member_type2 member_name2;
  member_type3 member_name3;
  .
  .
} object_names;

// The Sample code...
union mytypes_t {
  char c;
  int i;
  float f;
} mytypes;

// ...declares an object (mytypes) with three members
mytypes.c
mytypes.i
mytypes.f	

For italian people: la peculiarità della union è che tutte le sue variabili membro (in questo caso l’intero non segnato intero e l’array di char caratteri) condividono la stessa area di memoria, a partire dallo stesso indirizzo: in altri termini intero e caratteri occupano gli stessi 4 byte in memoria.
Tale proprietà si rivela molto utile, ad esempio, nella gestione dei colori in un ambiente grafico come X11. In un simile contesto, una union come quella del presente esempio consente di accedere “istantaneamente” alle componenti alpha, rossa, verde e blu del colore di un pixel senza ricorrere ad alcuna operazione di “bit masking” o “scorrimento bit”.

By |C++, Video Games Development|Commenti disabilitati su C++ Unions

C++ typedef

C++ typedef

A type alias is a different name by which a type can be identified. In C++, any valid type can be aliased so that it can be referred to with a different identifier.

For italian people: lo scopo della typedef è quello di assegnare dei nomi alternativi a dei tipi di dato esistenti, solitamente a quelli la cui dichiarazione standard è troppo ingombrante, magari confusionale, oppure per rendere il codice riutilizzabile più facilmente tra un’implementazione e un’altra.

Without typedf:

int current_speed ;
int high_score ;
...
 
void congratulate(int your_score) {
    if (your_score > high_score)
...

With typedef:

typedef int km_per_hour ;
typedef int points ;
 
km_per_hour current_speed ;
points high_score ;
...
 
void congratulate(points your_score) {
    if (your_score > high_score)
...

Entrambe le sezioni di codice implementano la stessa operazione. Ciononostante, l’uso della typedef nel secondo esempio rende più chiaro il fatto che, nonostante le due variabili sono rappresentate dallo stesso tipo di dato (int), le informazioni in esse contenute sono logicamente incompatibili.

My website: http://www.lucedigitale.com

Reference: http://it.wikipedia.org/wiki/Typedef

By |C++, Video Games Development|Commenti disabilitati su C++ typedef

C++ Data Structures – Arrow Operator

C++ Data Structures – Arrow Operator

A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.

Regular Variables

The syntax is:


// syntax
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

// working sample:
struct product {
  int weight;
  double price;
} apple, banana, melon;

// access
apple.weight
apple.price
banana.weight
banana.price
melon.weight
melon.price

Working sample:


// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// declare data structure
struct movies_t {
  string title;
  int year;
} mine, yours;

void printmovie (movies_t movie);

int main ()
{
  string mystr;

  mine.title = "2001 A Space Odyssey";
  mine.year = 1968;

  cout << "Enter title: ";
  getline (cin,yours.title); // store title
  cout << "Enter year: ";
  getline (cin,mystr);
  stringstream(mystr) >> yours.year; // store year

  cout << "My favorite movie is:\n ";
  printmovie (mine);
  cout << "And yours is:\n ";
  printmovie (yours);
  return 0;
}

void printmovie (movies_t movie)
{
  // access data structure
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

The result is:
Enter title: Alien
Enter year: 1979

My favorite movie is:
2001 A Space Odyssey (1968)
And yours is:
Alien (1979)

Arrays

You can use an Array into Data Structures:


// array of structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
} films [3];

void printmovie (movies_t movie);

int main ()
{
  string mystr;
  int n;

  for (n=0; n<3; n++)
  {
    cout << "Enter title: ";
    getline (cin,films[n].title);
    cout << "Enter year: ";
    getline (cin,mystr);
    stringstream(mystr) >> films[n].year;
  }

  cout << "\nYou have entered these movies:\n";
  for (n=0; n<3; n++)
    printmovie (films[n]);
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

The result is:
Enter title: Blade Runner
Enter year: 1982
Enter title: The Matrix
Enter year: 1999
Enter title: Taxi Driver
Enter year: 1976

You have entered these movies:
Blade Runner (1982)
The Matrix (1999)
Taxi Driver (1976)

Pointers to Data Structures


// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
};

int main ()
{
  string mystr;

  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;

  cout << "Enter title: ";
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;

  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";

  return 0;
}

The result is:
Enter title: Invasion of the body snatchers
Enter year: 1978

You have entered:
Invasion of the body snatchers (1978)

Arrow Operator

The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members. This operator serves to access the member of an object directly from its address.


// arrow operator
pmovie->title
// equivalent to:
(*pmovie).title

Working example:


// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
};

int main ()
{
  string mystr;

  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;

  cout << "Enter title: ";
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;

  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";

  return 0;
}

The result is:
Enter title: Invasion of the body snatchers
Enter year: 1978

You have entered:
Invasion of the body snatchers (1978)

Nesting (annidate) Structures

...
struct movies_t {
  string title;
  int year;
};

struct friends_t {
  string name;
  string email;
  movies_t favorite_movie;
} charlie, maria;

friends_t * pfriends = &charlie;
...
// After that it would be valid:
charlie.name
maria.favorite_movie.title
charlie.favorite_movie.year
pfriends->favorite_movie.year
...

My website: http://www.lucedigitale.com

Reference: http://www.cplusplus.com/doc/tutorial/structures/

By |C++, Video Games Development|Commenti disabilitati su C++ Data Structures – Arrow Operator