Ключевое слово this Указатель this доступен внутри метода объекта. Он указывает на сам объект, для которого вызван метод. Например: class Complex { private: float real, image; public: float get. Real() { return this->real; // тоже самое, что и return real; } } Пример использования: class Complex { private: float real, image; public: Complex& operator+=(const Complex& obj) { real += obj. real; image = obj. image; return *this; } } void main() { Complex c 1(1, 1), c 2(2, 2), c 3(3, 3); c 1+=c 2+=c 3; // c 2 станет (5, 5), а с1 станет (6, 6) }
Аргументы по умолчанию Проблема: дублирование кода Решение: class Date { private: int year, month, day; public: Date(int y, int m, int d) { year = y; month = m; day = d; } Date(int y, int m) { year = y; month = m; day = 1; } Date(int y) { year = y; month = 1; day = 1; } Date() { year = 1; month = 1; day = 1; } } class Date { private: int year, month, day; public: Date(int y=1, int m=1, int d=1) { year = y; month = m; day = d; } }