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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP