const metotlar
- C++ kursu
- Orta seviye
- Ders 26/116
- 5 dk
const metotlarla değiştirmeyen erişimi öğrenirsin.
const metotlar
Bir üye fonksiyonun imzasının sonuna const eklersen, o metod nesnenin üye değişkenlerini değiştiremez. Buna const metot denir. Bu, programcıya ve derleyiciye "bu metod nesneyi değiştirmez" sözünü verir.
Örnek: int getArea() const { return width * height; }. const sayesinde getArea içinde width = 5; gibi atama yapamazsın; derleme hatası alırsın. Ayrıca const bir nesne yalnızca const metotları çağırabilir. Bu, const correctness adı verilen bir C++ geleneğidir ve değişmezlik garantisini kodda açıkça belgelemeye yarar.
const nesneler
Bir nesneyi const olarak tanımlarsan, onun yalnızca const metotlarını çağırabilirsin. const Box b; yazarsan b.set(5) çağrısı derleme hatası verir; çünkü set nesneyi değiştirebilir. Ama b.getArea() çağrılabilir; çünkü getArea const'tur.
Bu ilke, sabit nesnelerin gerçekten değişmeden kalmasını garanti eder. Getter'ları her zaman const yapmak iyi bir alışkanlıktır: int getX() const { return x; }. Böylece hem sabit hem sabit olmayan nesnelerde çağrılabilirler. Setter'lar ise asla const olamaz; çünkü amaçları değiştirmektir.
Uygulama Box sınıfına const metot ekle
Box sınıfını tanımla. private: altına int width; ve int height; üye değişkenleri ekle. public: altına void setSize(int w, int h) { width = w; height = h; } ve int getArea() const { return width * height; } metotlarını ekle. main içinde Box b; oluştur, setSize(3, 4) çağır ve std::cout ile getArea()'yi yazdır.
Başlangıç kodu
#include <iostream>
// Box sınıfını tanımla
int main() {
// Box örneği oluştur, setSize çağır ve getArea yazdır
return 0;
}Örnek çözüm
#include <iostream>
class Box {
int width;
int height;
public:
void setSize(int w, int h) {
width = w;
height = h;
}
int getArea() const {
return width * height;
}
};
int main() {
Box b;
b.setSize(3, 4);
std::cout << b.getArea();
return 0;
}Beklenen çıktı
12
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Bildirimi rolüne eşle
| Kavram | Anlamı |
|---|---|
int get() const |
Değiştirmez |
void set(int x) |
Değiştirebilir |
const Box b; |
Sabit nesne |
b.get() |
Sabit nesnede çağrılır |
2 const anahtar kelimesini yaz
int getArea() ____ { return width * height; }
int getArea() const { return width * height; }
Açıklama: const, metodun nesneyi değiştirmeyeceğini belirtir.
3 const Box b; tanımından sonra hangisi çağrılabilir?
const Box b;- b.setWidth(5)
- b.width = 5
- b.area = 5
- b.getArea() Doğru cevap
Açıklama: const nesnede yalnızca const metotlar çağrılır.