在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
在这里我们可以看到当对象正常时调用了正常函数。当对象为常数时,将调用常数函数。
如果两个重载方法包含参数,并且一个参数是正常参数,另一个参数是常数,则将产生错误。
#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