C-Programmierung
Konstruktor Beispiel
← Destruktoren | ● | Dynamische Objekterzeugung →
Beispiel der Datenkapselung anhand einer Datums-Klasse:
Keine Datenkapselung mit C - Strukturen möglich, passive Zustandsänderung immer möglich:
struct Date
{
int day, month, year;
};
Date date = {1, 1, 2004};
date.year=2000;
date.month=13; -> inconsistent date
{
int day, month, year;
};
Date date = {1, 1, 2004};
date.year=2000;
date.month=13; -> inconsistent date
Datenkapselung mit C++ - Klassen möglich, keine passive Zustandsänderung möglich, nur aktiv:
class Date
{
public:
Date()
{
day_=1;
month_=1;
year_=0;
}
Date(int day,int month,int year)
{
day_=day;
month_=month;
year_=year;
}
void get(int &day, int &month, int &year)
{
day=day_;
month=month_;
year=year_;
}
void set(const int &day, const int &month, const int &year)
{
if (day<1 || day>31) throw std::invalid_argument("invalid day")
if (month<1 || month>12) throw std::invalid_argument("invalid month")
day_=day;
month_=month;
year_=year;
}
bool isleapyear()
{
return((year_%4==0 && year_%100!=0) || year_%400==0);
}
protected:
int day_, month_, year_;
};
Date date(1, 1, 2004);
date.year_=2000; -> compiler error due to access of protected member variable
date.set(1,13,2000); -> run time error due to uncatched exception
date.set(1,1,2000);
date.isleapyear() -> false;
{
public:
Date()
{
day_=1;
month_=1;
year_=0;
}
Date(int day,int month,int year)
{
day_=day;
month_=month;
year_=year;
}
void get(int &day, int &month, int &year)
{
day=day_;
month=month_;
year=year_;
}
void set(const int &day, const int &month, const int &year)
{
if (day<1 || day>31) throw std::invalid_argument("invalid day")
if (month<1 || month>12) throw std::invalid_argument("invalid month")
day_=day;
month_=month;
year_=year;
}
bool isleapyear()
{
return((year_%4==0 && year_%100!=0) || year_%400==0);
}
protected:
int day_, month_, year_;
};
Date date(1, 1, 2004);
date.year_=2000; -> compiler error due to access of protected member variable
date.set(1,13,2000); -> run time error due to uncatched exception
date.set(1,1,2000);
date.isleapyear() -> false;
← Destruktoren | ● | Dynamische Objekterzeugung →