C++ 中的函数重载和 const 关键字
c++server side programmingprogramming更新于 2025/4/23 15:22:17
在 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