Objekt-Orientierte Programmierung in C++ erlaubt die Modellierung von Objekten mit Daten und Funktionen. Diese Lektion behandelt Klassen, Objekte, Konstruktoren und Methoden.
class Punkt {
public:
int x, y; // Attribute
void print() { // Methode
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Punkt p1;
p1.x = 3;
p1.y = 4;
p1.print();
return 0;
}
class Punkt {
public:
int x, y;
Punkt(int a, int b) : x(a), y(b) {} // Konstruktor
void print() {
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Punkt p2(5,7);
p2.print();
return 0;
}
public, private und protected geregelt.
class Kreis {
private:
double radius;
public:
Kreis(double r) : radius(r) {}
double flaeche() { return 3.14159 * radius * radius; }
};
int main() {
Kreis k(2.0);
std::cout << "Fläche: " << k.flaeche() << std::endl;
return 0;
}
private sein, Methoden public