C ++中的函数重载和const关键字
在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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语