Перегрузка операторов

Последнее обновление: 04.05.2024

C++

C#

Dart

Kotlin

Python

Rust

C++

#include <iostream>
 
class Counter
{
public:
    Counter(int val)
    {
        value =val;
    }
    void print() 
    {
        std::cout << "Value: " << value << std::endl;
    }
    Counter operator + (const Counter& counter) const
    {
        return Counter{value + counter.value};
    }
private:
    int value;
};

int main()
{
    Counter c1{20};
    Counter c2{10};
    Counter c3 = c1 + c2;
    c3.print();   // Value: 30
}

C#

Counter c1 = new(5);
Counter c2 = new(15);
Counter c3 = c1 + c2;
Console.WriteLine(c3.Value); // 20

class Counter
{
    public int Value {get;}
    public Counter(int value)
    {
        this.Value = value;
    }

    public static Counter operator +(Counter counter1, Counter counter2)
    {
        return new Counter (counter1.Value + counter2.Value);
    }
}

Dart

class Counter{
     
    int value;
    Counter(this.value);
     
    Counter operator +(Counter otherCounter){
         
        return Counter(this.value + otherCounter.value);
    }
}
void main (){
      
    Counter counter1 = Counter(5);
    Counter counter2 = Counter(15);
    Counter counter3 = counter1 + counter2;
    print(counter3.value);  // 20
}

Kotlin

fun main() {

    val counter1 = Counter(5)
    val counter2 = Counter(15)
    val counter3 = counter1 + counter2
    println(counter3.value) // 20
}
class Counter(var value: Int){
    operator fun plus(counter: Counter): Counter {
        return Counter(this.value + counter.value)
    }
}

Python

class Counter:
    def __init__(self, value):
        self.value = value
        
    def __add__(self, other):
        return Counter(self.value + other.value)
    
counter1 = Counter(5)
counter2 = Counter(15)
counter3 = counter1 + counter2
print(counter3.value)       # 20

Rust

use std::ops::Add;  // поключаем трейт Add из модуля std::ops

struct Counter{ 
    value: u32
}

impl Add for Counter{

    type Output = Counter; // тип генерируемого значения
    fn add(self, other: Counter) -> Counter { 
        Counter {
            value: self.value + other.value
        }
    }
}
fn main() {

    let counter1 = Counter{value:5};
    let counter2 = Counter{value:15};
    let counter3 = counter1 + counter2;
    println!("{}", counter3.value);  // 20
}
Помощь сайту
Юмани:
410011174743222
Перевод на карту
Номер карты:
4048415020898850