C++에서는 함수를 오버로드할 수 있습니다. 일부 기능은 일반 기능입니다. 일부는 상수 유형 함수입니다. 상수 함수와 일반 함수에 대한 아이디어를 얻기 위해 하나의 프로그램과 그 출력을 보겠습니다.
예시
#include <iostream>
using namespace std;
class my_class {
public:
void my_func() const {
cout << "Calling the constant function" << endl;
}
void my_func() {
cout << "Calling the normal function" << endl;
}
};
int main() {
my_class obj;
const my_class obj_c;
obj.my_func();
obj_c.my_func();
} 출력
Calling the normal function Calling the constant function
여기서 우리는 객체가 normal일 때 normal 함수가 호출되는 것을 볼 수 있습니다. 객체가 상수일 때 상수 함수가 호출됩니다.
두 개의 오버로드된 메서드에 매개변수가 포함되어 있고 한 매개변수는 정상이고 다른 매개변수는 상수이면 오류가 발생합니다.
예시
#include <iostream>
using namespace std;
class my_class {
public:
void my_func(const int x) {
cout << "Calling the function with constant x" << endl;
}
void my_func(int x){
cout << "Calling the function with x" << endl;
}
};
int main() {
my_class obj;
obj.my_func(10);
} 출력
[Error] 'void my_class::my_func(int)' cannot be overloaded [Error] with 'void my_class::my_func(int)'
그러나 인수가 참조 또는 포인터 유형이면 오류가 발생하지 않습니다.
예시
#include <iostream>
using namespace std;
class my_class {
public:
void my_func(const int *x) {
cout << "Calling the function with constant x" << endl;
}
void my_func(int *x) {
cout << "Calling the function with x" << endl;
}
};
int main() {
my_class obj;
int x = 10;
obj.my_func(&x);
} 출력
Calling the function with x