산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C++ 연산자 오버로딩

C++ 연산자 오버로딩

이 튜토리얼에서는 예제를 통해 연산자 오버로딩에 대해 배울 것입니다.

C++에서는 객체 및 구조와 같은 사용자 정의 유형에 대해 연산자가 작동하는 방식을 변경할 수 있습니다. 이를 연산자 과부하라고 합니다. . 예를 들어,

세 개의 객체 c1를 생성했다고 가정합니다. , c2결과 Complex이라는 클래스에서 복소수를 나타냅니다.

연산자 오버로딩을 통해 연산자의 작동 방식을 변경할 수 있으므로 + 연산자가 작동하고 이를 사용하여 c1의 복소수를 추가합니다. 및 c2 다음 코드를 작성하여:

result = c1 + c2;

대신

result = c1.addNumbers(c2);

따라서 코드가 직관적이고 이해하기 쉽습니다.

참고: int과 같은 기본 데이터 유형에는 연산자 오버로딩을 사용할 수 없습니다. , float , char 등등.

<시간>

C++ 연산자 오버로딩을 위한 구문

연산자를 오버로드하기 위해 특수 operator을 사용합니다. 기능. 우리는 오버로드된 연산자가 작업하기를 원하는 객체/변수가 있는 클래스 또는 구조 내부에 함수를 정의합니다.

class className {
    ... .. ...
    public
       returnType operator symbol (arguments) {
           ... .. ...
       } 
    ... .. ...
};

여기,

<시간>

단항 연산자의 연산자 오버로딩

단항 연산자는 하나의 피연산자에서만 작동합니다. 증가 연산자 ++ 및 감소 연산자 -- 단항 연산자의 예입니다.

<시간>

예제 1:++ 연산자(단항 연산자) 오버로딩

// Overload ++ when used as prefix

#include <iostream>
using namespace std;

class Count {
   private:
    int value;

   public:

    // Constructor to initialize count to 5
    Count() : value(5) {}

    // Overload ++ when used as prefix
    void operator ++ () {
        ++value;
    }

    void display() {
        cout << "Count: " << value << endl;
    }
};

int main() {
    Count count1;

    // Call the "void operator ++ ()" function
    ++count1;

    count1.display();
    return 0;
}

출력

Count: 6

여기서 ++count1;을 사용하면 , void operator ++ () 라고 합니다. 이것은 을 증가시킵니다. count1 개체의 속성 1.

참고: 연산자를 오버로드하면 원하는 방식으로 작동하도록 사용할 수 있습니다. 예를 들어 ++을 사용할 수 있습니다. 증가 100.

그러나 이것은 우리의 코드를 혼란스럽고 이해하기 어렵게 만듭니다. 연산자 오버로딩을 일관되고 직관적인 방식으로 적절하게 사용하는 것은 프로그래머로서 우리의 임무입니다.

<시간>

위의 예는 ++일 때만 작동합니다. 접두사로 사용됩니다. ++을 만들려면 이 구문을 사용하는 접미사로 작동합니다.

void operator ++ (int) {
    // code
}

int 주목 괄호 안에. 단항 연산자를 접미사로 사용하는 데 사용되는 구문입니다. 함수 매개변수가 아닙니다.

<시간>

예제 2:++ 연산자(단항 연산자) 오버로딩

// Overload ++ when used as prefix and postfix

#include <iostream>
using namespace std;

class Count {
   private:
    int value;

   public:

    // Constructor to initialize count to 5
    Count() : value(5) {}


    // Overload ++ when used as prefix
    void operator ++ () {
        ++value;
    }


    // Overload ++ when used as postfix
    void operator ++ (int) {
        value++;
    }

    void display() {
        cout << "Count: " << value << endl;
    }
};

int main() {
    Count count1;

    // Call the "void operator ++ (int)" function
    count1++;
    count1.display();

    // Call the "void operator ++ ()" function
    ++count1;

    count1.display();
    return 0;
}

출력

Count: 6
Count: 7
<시간>

예시 2 ++일 때 작동 접두사와 접미사로 모두 사용됩니다. 그러나 다음과 같이 하려고 하면 작동하지 않습니다.

Count count1, result;

// Error
result = ++count1;

이는 연산자 함수의 반환 유형이 void이기 때문입니다. . Count을 만들어 이 문제를 해결할 수 있습니다. 연산자 함수의 반환 유형으로.

// return Count when ++ used as prefix

Count operator ++ () {
    // code
}

// return Count when ++ used as postfix

Count operator ++ (int) {
   // code
}
<시간>

예제 3:연산자 함수의 반환 값(++ 연산자)

#include <iostream>
using namespace std;

class Count {
   private:
    int value;

   public
       :
    // Constructor to initialize count to 5
    Count() : value(5) {}

    // Overload ++ when used as prefix
    Count operator ++ () {
        Count temp;

        // Here, value is the value attribute of the calling object
        temp.value = ++value;

        return temp;
    }

    // Overload ++ when used as postfix
    Count operator ++ (int) {
        Count temp;

        // Here, value is the value attribute of the calling object
        temp.value = value++;

        return temp;
    }

    void display() {
        cout << "Count: " << value << endl;
    }
};

int main() {
    Count count1, result;

    // Call the "Count operator ++ ()" function
    result = ++count1;
    result.display();

    // Call the "Count operator ++ (int)" function
    result = count1++;
    result.display();

    return 0;
}

출력

Count: 6
Count: 6

여기에서 접두사 오버로딩을 위해 다음 코드를 사용했습니다.

// Overload ++ when used as prefix
Count operator ++ () {
    Count temp;

    // Here, value is the value attribute of the calling object
    temp.value = ++value;

    return temp;
}

후위 연산자 오버로딩을 위한 코드도 유사합니다. temp 객체를 생성했음을 주목하세요. 연산자 함수에 값을 반환했습니다.

또한 코드를 확인하십시오.

temp.value = ++value; 

변수 count1에 속함 main()의 개체 count1 때문에 함수를 호출하는 동안 temp.value temp에 속함 개체.

<시간>

이진 연산자의 연산자 오버로딩

이항 연산자는 두 개의 피연산자에서 작동합니다. 예를 들어,

result = num + 9;

여기, + 피연산자 num에서 작동하는 이항 연산자입니다. 및 9 .

코드를 사용하여 사용자 정의 유형에 대한 이항 연산자를 오버로드하는 경우:

obj3 = obj1 + obj2;

연산자 함수는 obj1을 사용하여 호출됩니다. 개체 및 obj2 함수에 인수로 전달됩니다.

<시간>

예제 4:C++ 이진 연산자 오버로딩

// C++ program to overload the binary operator +
// This program adds two complex numbers

#include <iostream>
using namespace std;

class Complex {
   private:
    float real;
    float imag;

   public:
    // Constructor to initialize real and imag to 0
    Complex() : real(0), imag(0) {}

    void input() {
        cout << "Enter real and imaginary parts respectively: ";
        cin >> real;
        cin >> imag;
    }

    // Overload the + operator
    Complex operator + (const Complex& obj) {
        Complex temp;
        temp.real = real + obj.real;
        temp.imag = imag + obj.imag;
        return temp;
    }

    void output() {
        if (imag < 0)
            cout << "Output Complex number: " << real << imag << "i";
        else
            cout << "Output Complex number: " << real << "+" << imag << "i";
    }
};

int main() {
    Complex complex1, complex2, result;

    cout << "Enter first complex number:\n";
    complex1.input();

    cout << "Enter second complex number:\n";
    complex2.input();

   // complex1 calls the operator function
   // complex2 is passed as an argument to the function
    result = complex1 + complex2;
    result.output();

    return 0;
}

출력

Enter first complex number:
Enter real and imaginary parts respectively: 9 5
Enter second complex number:
Enter real and imaginary parts respectively: 7 6
Output Complex number: 16+11i

이 프로그램에서 연산자 함수는 다음과 같습니다.

Complex operator + (const Complex& obj) {
    // code
}

이 대신 다음과 같이 이 함수를 작성할 수도 있습니다.

Complex operator + (Complex obj) {
    // code
}

그러나

<그림> <시간>

C++ 연산자 오버로딩에서 기억해야 할 사항

  1. 연산자 2개 =& C++에서는 기본적으로 이미 오버로드되어 있습니다. 예를 들어 동일한 클래스의 객체를 복사하려면 =을 직접 사용할 수 있습니다. 운영자. 연산자 함수를 만들 필요가 없습니다.
  2. 연산자 오버로딩은 연산자의 우선 순위와 연관성을 변경할 수 없습니다. 그러나 평가 순서를 변경하려면 괄호를 사용해야 합니다.
  3. C++에서 오버로드할 수 없는 4개의 연산자가 있습니다. 그들은:
    1. :: (범위 해상도)
    2. . (멤버 선택)
    3. .* (함수 포인터를 통한 멤버 선택)
    4. ?: (삼항 연산자)
<시간>

다음 페이지를 방문하여 자세히 알아보십시오.


C 언어

  1. C# 연산자
  2. C# 삼항(? :) 연산자
  3. C# 메서드 오버로딩
  4. C# 생성자 오버로딩
  5. C++ 연산자
  6. C++ 주석
  7. C++ 클래스 템플릿
  8. 파이썬 연산자 오버로딩
  9. 예제가 있는 C++의 연산자:정의, 유형 및 프로그램
  10. 예제를 사용한 C++ 연산자 오버로딩