Sie sind auf Seite 1von 13

Seminar 2

#include <iostream>
using namespace std;
//transmitere prin valoare (passsing by value)
void sum(int x, int y)
{
x = x + y;
}
//transmitere prin adresa/pointer (passsing by address/pointer)
void sum_a(int* x, int y)
{
*x = *x + y;
}
//transmitere prin referinta (passsing by reference)
void sum_r(int&x, int y)
{
x = x + y;
}
int main()
{
int x = 5;
int* px;
px = &x;
cout << *px << "\n";
int& y = x;
x++;
cout << y << endl;
int* py = px + 2;
py--;
cout << py - px << endl;
int a = 3, b = 7;
sum(a, b);
cout << a << endl;
sum_a(&a, b);
cout << a << endl;
sum_r(a, b);
cout << a << endl;
//alocarea de spatiu pt un double in heap cu malloc (allocating space for one
double in heap with malloc)
double* pd = (double*)malloc(sizeof(double));
*pd = 1.2;
cout << *pd << endl;
free(pd);
pd = NULL;

//acelasi lucru cu new (the same thing with new)


pd = new double();
*pd = 1.2;
cout << *pd << endl;
delete pd;
pd = NULL;
//vector alocat static (statically allocated vector)
double v[20];
v[0] = 0; v[1] = 1; v[2] = 2;
cout << v << endl;
cout << *(v + 2) << endl;
//vector alocat dinamic (dinamucally allocated vector)
int n = 10;
//malloc nu este folosit in POO (malloc in not used anymore in OOP)
//double* w = (double*)malloc(n * sizeof(double));
double* w = new double[n];
w[0] = 1; w[1] = 2; w[2] = 3;
cout << *(w + 2) << endl;
delete[] w;

//sirurile de caractere sunt vectori, nu pot fi copiati cu egal (strings in C


are vector, they cannot be copied with equals)
//char s[20] = "OOP";
char s[20];
//se folosesc functii speciale pentru asta (we use specific functions for
this)
strcpy(s, "OOP");
cout << strlen(s) << endl;
strcpy(s, "Hello, world!");
cout << strlen(s) << endl;
}

Seminar 3
#include <iostream>
#include <string>
using namespace std;

//array is passed by reference


//if we erase the &, it will be just a pointer passed by value
//once we change the address saved by that pointer
//all the other changes will not be visible in main
void add_element(float*& array, int size, float value)
{
//we cannot add an element in a dinamically allocated array directly
//first we copy all the values in a local array
float* buffer = new float[size];
for (int i = 0; i < size; i++)
{
buffer[i] = array[i];
}

//then we deallocate the existing array


delete[] array;
//and we allocate a larger memory space
array = new float[size + 1];
//we copy the values back from the local array
for (int i = 0; i < size; i++)
{
array[i] = buffer[i];
}
//we set the last element to be the value that we want to add
array[size] = value;
//and we deallocate the local array
delete[] buffer;
}
int main()
{
char s[20];
//strcpy is unsafe
//the best approach is to use strcpy_s instead
//strcpy_s has two parameters for static arrays
strcpy_s(s, "OOP");
cout << s << endl;

char* t = new char[strlen("hello") + 1];


//and three parameters for dinamically allocated arrays
//the second parameters is the size of the source (including /0)
strcpy_s(t, strlen("hello") + 1,"hello");
cout << t << endl;
delete[] t; t = NULL;

//string is an easier way to work with strings


//it is available in C++ only
string a = "something";
a = "something else";
string b = a + "!!!";
cout << a << " " << b << endl;

//static matrix
int m[2][3] = { {1, 2, 3}, {4, 5, 6} };

cout << m[1][2] << endl;

//dinamically allocated matrix


///first we allocate in heap an array with 2 elements of type int*
int** w = new int*[2];
//then each element of this array saves the address of another array of int
for (int i = 0; i < 2; i++)
{
w[i] = new int[3];
}
w[1][2] = 99;
cout << *(*(w + 1) + 2) << endl;

//allways we deallocate memory in the reverse order of the allocation


for (int i = 0; i < 2; i++)
{
delete[] w[i];
}
delete[] w;
w = NULL;
float* z = new float[3];
z[0] = 2; z[1] = 2; z[2] = 2;

add_element(z, 3, 5);
for (int i = 0; i < 4; i++)
{
cout << z[i] << " ";
}
delete[] z; z = NULL;
}
Seminar 4

#include <iostream>
#include <string>
using namespace std;
struct person
{
char firstName[40];
string surname;
int age;
float height;
};

class Person
{
//accessible just for this class
private:
char firstName[40];
//accessible for this class and all the inherited classes
protected:
float height;
//accessible for everyone
public:
string surname;
int age;

//default constructor (parameterless constructor)


Person()
{
strcpy_s(firstName, "Anonymous");
surname = "";
age = 0;
height = 0.3f;
}
//constructor with parameters
Person(const char fn[40], string s, float h)
{
strcpy_s(firstName, fn);
surname = s;
height = h;
age = 0;
}
//inline method
void init(const char fn[40], string s, int a, float h)
{
strcpy_s(firstName, fn);
surname = s;
age = a;
height = h;
}
//access method (getter)
float get_height()
{
return height;
}
//access method (setter)
void set_height(float h)
{
if (h > 0)
{
height = h;
}
}
//outline method signature
char* return_firstName();
};
//outline method definition
char* Person::return_firstName()
{
return firstName;
}
int main()
{
//variable p1 of type person
person p1 = { "Gregor", "Smith", 31, 1.78f };
strcpy_s(p1.firstName, "John");
cout << p1.surname << endl;
//pointer to person which is structure
person* pp;
pp = &p1;
cout << (*pp).firstName << endl;
cout << pp->age << endl;

//variable p2 is an object of type Person


//default constructor is automatically called
Person p2;
p2.init("Daniel", "Greg", 40, 1.83f);

cout << p2.surname << endl;


//Pointer to object (of type Person)
Person* pc;
pc = &p2;

cout << pc->age << endl;


//constructor with parameters is called
Person p3("Michael", "McGregor", 1.98f);
cout << p3.return_firstName() << endl;
p3.set_height(1.88f);
cout << p3.get_height() << endl;
}

Seminar 5 + 6+7
#include <iostream>
#include <string>
using namespace std;

class FootballTeam
{
private:
//constant fields should be initialized at declaration or in the constructors
const int id;
string name;
unsigned matches_played;
unsigned* goals_scored;
public:
//static field | it is common for all the objects | it is saved at class
level, not at instance level
static int nb_of_players;
//default constructor | constant field initializing is mandatory
FootballTeam() : id(0)
{
name = "";
matches_played = 0;
goals_scored = NULL;
}
//constructor with 2 parameters
FootballTeam(int id, string name) : id(id)
{
//the usage of this is mandatory, otherwise the argument will hide the
attribute
this->name = name;
matches_played = 0;
goals_scored = NULL;
}
//constructor with 3 parameters
FootballTeam(string name, unsigned matches_played, unsigned*
goals_scored) : id(2)
{
this->name = name;
this->matches_played = matches_played;
//goals_scored cannot be copied with =, it would be a shallow copy
if (goals_scored != NULL)
{
this->goals_scored = new unsigned[matches_played];
for (unsigned i = 0; i < matches_played; i++)
{
this->goals_scored[i] = goals_scored[i];
}
}
else
{
this->matches_played = 0;
this->goals_scored = NULL;
}
}

//copy constructor
FootballTeam(const FootballTeam& t) : id(t.id)
{ name = t.name;
matches_played = t.matches_played;
if (t.goals_scored)
{ goals_scored = new unsigned[matches_played];
for (unsigned i = 0; i < matches_played; i++)
{
goals_scored[i] = t.goals_scored[i];
}
}
else
{
matches_played = 0;
goals_scored = NULL;
}
}

//destructor
~FootballTeam()
{
if (goals_scored != NULL)
{
delete[] goals_scored;
}
}

//equals operator
FootballTeam& operator=(const FootballTeam& t)
{
if (goals_scored)
{
delete[] goals_scored;
}

name = t.name;
matches_played = t.matches_played;

if (t.goals_scored)
{
goals_scored = new unsigned[matches_played];
for (unsigned i = 0; i < matches_played; i++)
{
goals_scored[i] = t.goals_scored[i];
}
}
else
{
matches_played = 0;
goals_scored = NULL;
}

return *this;
}

//getter for name


string get_name()
{
return name;
}

//setter for name with validation


void set_name(string new_name)
{
if (new_name.length() > 0)
{
name = new_name;
}
}

//getter for matches played


unsigned get_matches_played()
{
return matches_played;
}

//getter for goals_scored | it should return a copy, otherwise it will act


like a setter too
unsigned* get_goals_scored()
{
if (goals_scored != NULL)
{
unsigned* copy = new unsigned[matches_played];
for (unsigned i = 0; i < matches_played; i++)
{
copy[i] = goals_scored[i];
}
return copy;
}
return NULL;
}

//setter for goals_scored and matches_played | both of them should be set


simultaneously because they depend on each other
void set_goals(unsigned matches, unsigned* goals)
{
if (goals_scored != NULL)
{
delete[] goals_scored;
}
if (goals != NULL)
{
goals_scored = new unsigned[matches];
matches_played = matches;
for (unsigned i = 0; i < matches; i++)
{
goals_scored[i] = goals[i];
}
}
else
{
goals_scored = NULL;
matches_played = 0;
}
}

//static method | it doesn't compute something related to the instance


(this), but it should be member of the class
static unsigned long TotalGoalsScoredInChampionship(unsigned nb_of_teams,
FootballTeam* teams)
{
unsigned long result = 0;
if (nb_of_teams > 0)
{
for (unsigned i = 0; i < nb_of_teams; i++)
{
FootballTeam t = teams[i];
if (t.matches_played > 0)
{
for (unsigned j = 0; j < t.matches_played; j++)
{
result += t.goals_scored[j];
}
}
}
}
return result;
}

//pre-incrementation operator
FootballTeam& operator++()
{
this->goals_scored[matches_played - 1]++;
return *this;
}

//post-incrementation operator
FootballTeam operator++(int i)
{
FootballTeam copy = *this;
this->goals_scored[matches_played - 1]++;
return copy;
}

//addition operator (works just for adding FootballTeam and unsigned values,
not vice versa)
FootballTeam operator+(unsigned value)
{
FootballTeam copy = *this;
copy.goals_scored[copy.matches_played - 1] += value;
return copy;
}

//index operator (read/write mode) / if we want it readonly we should return


unsigned instead of unsigned&
unsigned& operator[](unsigned index)
{
return goals_scored[index];
}

//the explicit cast to long operator


explicit operator long()
{
long result = 0;
if (goals_scored != NULL)
{
for (unsigned i = 0; i < matches_played; i++)
{
result += goals_scored[i];
}
}
return result;
}

//less than operator


//it uses the cast to long operator to compare objects in therms of total
number of goals
bool operator<(FootballTeam t)
{
return (long)*this < (long)t;
}

//addition operator (works for adding unsigned and FootballTeam values, to


preserve the commutativity)
//this is not the operator per se, it's just an announcement to let the class
know that this function can access private fields
friend FootballTeam operator+(unsigned, FootballTeam);

//output operator announced as friend function


friend ostream& operator<<(ostream&, FootballTeam);
};

//static field instantiation


int FootballTeam::nb_of_players = 11;

//the implementation of the second addition operator as a global function


//it cannot be overloaded as a member of the class because the first operand
is not of type FootballTeam
FootballTeam operator+(unsigned value, FootballTeam t)
{
t.goals_scored[t.matches_played - 1] += value;
return t;
}

//the input operator overloaded as a global function


//the function is not declared friend in the class because it is making use
of setters instead of accessing private fields
istream& operator>>(istream& in, FootballTeam& t)
{
string name;
cout << "Name: ";
in >> name;
t.set_name(name);
unsigned nb;
cout << "Nb of matches:";
in >> nb;

unsigned* array = new unsigned[nb];


for (unsigned i = 0; i < nb; i++)
{
cout << "Goals scored in match " << (i + 1) << ": ";
in >> array[i];
}
t.set_goals(nb, array);
delete[] array;

return in;
}
//the output operator
ostream& operator<<(ostream& out, FootballTeam t)
{
out << "Name: " << t.name << endl;
out << "Matches played: " << t.matches_played << endl;
out << "Goals scored per match: ";
if(t.goals_scored)
{
for (unsigned i = 0; i < t.matches_played; i++)
{
out << t.goals_scored[i] << " ";
}
}
else
{
out << "none";
}
out << endl;
return out;
}

//just an empty function which shows that the copy constructor is called when
passing an object by value
void DoNothing(FootballTeam t)
{

int main()
{
//anonymous block to force the call of the destructor at the end
{
//default constructor is called
FootballTeam t1;
}
//contructor with 2 parameters is called, 99 is the id that cannot be
modified anymore
FootballTeam t2(99, "Real Madrid");
unsigned v[] = { 3, 3, 3, 1, 2 };

//constructor with 3 parameters is called


FootballTeam t3("FC Barcelona", 5, v);

cout << t3.get_name() << endl;


cout << t3.get_matches_played() << endl;
cout << "Goals scored: ";
unsigned* g = t3.get_goals_scored();
g[0] = 99;
for (unsigned i = 0; i < t3.get_matches_played(); i++)
{
cout << g[i] << " ";
}
//because we return a copy from get_goals_scored() is the job of the caller
to deallocate the returned array
delete[] g;
//just before the program ends, the destructor will be called for t2 and t3
//copy constructor call
FootballTeam t4 = t3;

unsigned w[] = { 0, 0, 1 };
t3.set_goals(3, w);
DoNothing(t3);

FootballTeam t5;
//equals operator call
t5 = t4;

t5.set_goals(3, w);

//pointer to Football team


FootballTeam* p;
p = &t2;
p = new FootballTeam();
p->set_name("Arsenal");
cout << p->get_name() << endl;

//FootballTeam* q = p;
//deep copy of the object that p points to into another object that q
will point to
FootballTeam* q = new FootballTeam(*p);

//the deallocation for pointers that are saving objects' addresses is


mandatory
delete p;
delete q;

//displays 11
cout << t3.nb_of_players << endl;
t4.nb_of_players++;

//displays 12 because nb_of_players is shared between different objects


cout << t3.nb_of_players << endl;

t3.nb_of_players--;

//displays 11 | we don't necessary need an instance of the class to acces the


static field
cout << FootballTeam::nb_of_players << endl;

FootballTeam teams[] = { t3, t4 };

//static method call


cout << FootballTeam::TotalGoalsScoredInChampionship(2, teams) <<
endl;

//operators testing
FootballTeam t6 = ++t3;
FootballTeam t7 = t3++;
FootballTeam t8 = t3 + 4;
FootballTeam t9 = 4 + t3;

FootballTeam t10;
cin >> t10 >> t3;
cout << t3 << t4;

//index operator in write mode


t4[1] = 11;

//index operator in read mode


cout << t4[1] << endl;

//explicit cast operator call


cout << (long)t9 << endl;

//less than operator call


if (t3 < t9)
{
cout << "t3 scored fewer goals than t9" << endl;
}
else
{
cout << "t9 scored fewer goals than t3" << endl;
}
}

Das könnte Ihnen auch gefallen