Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 오버로드할 수 없는 함수

<시간/>

함수 오버로딩은 메서드 오버로딩이라고도 합니다. 함수 오버로딩은 객체 지향 프로그래밍에서 널리 사용되는 다형성 개념에서 제공하는 기능입니다.

함수 오버로딩을 달성하려면 함수는 다음 조건을 충족해야 합니다. -

  • 함수의 반환 유형은 동일해야 합니다.

  • 함수의 이름은 동일해야 합니다.

  • 매개변수의 유형은 다를 수 있지만 숫자는 동일해야 합니다.

예시

int display(int a); int display(float a); // both the functions can be overloaded
int display(int a); float display(float b); //both the functions can’t be overloaded as the return type of
one function is different from another

C++에서 오버로드할 수 없는 함수에 대해 알아보겠습니다.

  • 다른 이름과 다른 수의 매개변수를 가진 함수

예시

#include<iostream>
using namespace std;
int max_two(int a, int b) //contains two parameters{
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
int max_three(int a, int b ,int c) //contains three parameters{
   if (a>b && a>c){
      return a;
   }
   else if(b>c){
      return b;
   }
   else{
      return c;
   }
}
int main(){
   max_two(a,b);
   return 0;
}
  • 이름은 같지만 반환 유형이 다른 함수

예시

#include<iostream>
using namespace std;
int max_two(int a, int b){
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
float max_two(int a, int b){
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
int main(){
   max_two(a, b);
   return 0;
}
  • 함수 오버로딩의 모든 조건을 만족하지만 정적 멤버 함수인 경우 오버로딩할 수 없는 멤버 함수입니다.

예시

#include<iostream>
class check{
   static void test(int i)
   { }
   void test(int i)
   { }
};
int main(){
   check ch;
   return 0;
}
  • 두 함수가 정확히 같지만 기본 인수만 다른 경우(예:함수 중 하나에 기본 인수가 포함된 경우) 동일한 것으로 간주되어 오버로드될 수 없으므로 컴파일러에서 동일한 함수의 재선언 오류가 발생합니다.

예시

#include<iostream>
#include<stdio.h>
using namespace std;
int func_1 ( int a, int b){
   return a*b;
}
int func_1 ( int a, int b = 40){
   return a+b;
}
Int main(){
   func_1(10,20);
   return 0;
}