CodeBlanks Logo Icon CodeBlanks

Operatör fonksiyonu

operatör fonksiyonu tanımlamayı öğrenirsin.

Operatör fonksiyonu

Bir operatör fonksiyonu, +, -, == gibi operatörleri kendi sınıfın için yeniden tanımlar. Fonksiyon adı operator kelimesi ve operatör sembolünden oluşur.

Örnek: Vector2 operator+(const Vector2& other) const;. Bu, iki Vector2 nesnesini + ile toplamayı sağlar. Çağrı: Vector2 c = a + b; aslında a.operator+(b) çağırır. const ile metodun nesneyi değiştirmediği belirtilir. Operatör aşırı yükleme, sınıfları yerleşik türler gibi doğal kullanmanı sağlar.

Üye olarak tanımlama

Bir operatör fonksiyonu sınıfın üyesi olarak tanımlanabilir. Bu durumda sol taraf nesnenin kendisi, sağ taraf ise parametredir.

Örnek: Vector2 operator+(const Vector2& other) const { return Vector2(x + other.x, y + other.y); }. Burada this->x ile other.x toplanır ve yeni bir Vector2 döndürülür. a + b ifadesi a üzerinden operator+ çağırır ve b'yi parametre olarak verir. const metodu a'yı değiştirmez; bu yüzden a + b sonrası a aynı kalır.

Uygulama Vector2 sınıfına operator+ ekle

Başlangıç kodundaki Vector2 sınıfına operator+ ekle: gövdesi return Vector2(x + other.x, y + other.y);. main içinde a + b'yi hesapla ve sonucun x ve y'sini std::cout ile yazdır.

Başlangıç kodu

main.cpp
#include <iostream>

class Vector2 {
public:
    int x;
    int y;
    Vector2(int x_, int y_) : x(x_), y(y_) {}
    // Toplama operatörünü ekle
};

int main() {
    Vector2 a(1, 2);
    Vector2 b(3, 4);
    // a + b'yi hesapla ve sonucu yazdır
    return 0;
}

Örnek çözüm

main.cpp
#include <iostream>

class Vector2 {
public:
    int x;
    int y;
    Vector2(int x_, int y_) : x(x_), y(y_) {}
    Vector2 operator+(const Vector2& other) const {
        return Vector2(x + other.x, y + other.y);
    }
};

int main() {
    Vector2 a(1, 2);
    Vector2 b(3, 4);
    Vector2 c = a + b;
    std::cout << c.x << " " << c.y;
    return 0;
}

Beklenen çıktı

4 6

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 Operatör fonksiyonu adını tamamla

Soru
Vector2 ____(const Vector2& other) const;
Cevap
Vector2 operator+(const Vector2& other) const;

Açıklama: operator+ fonksiyonu + operatörünü tanımlar.

2 a + b ifadesi ne çağırır?

main.cpp
Vector2 a(1,2), b(3,4);
Vector2 c = a + b;
  • a.operator+(b) Doğru cevap
  • operator+(a, b)
  • b.operator+(a)
  • a.plus(b)

Açıklama: a + b, a üzerinde operator+ çağırır ve b'yi parametre verir.

3 Parçayı rolüne eşle

Kavram Anlamı
operator+ Toplama
operator Ön ek
const Değiştirmez
return Vector2( Yeni nesne döndürme

Orta seviye bölümündeki tüm dersler