C++ 类函数声明中,'const' 放置在末尾的含义是什么?
有时,我们会在函数声明的末尾发现关键字“const”。那么它是什么意思呢?
使用这种语法可以让一个函数成为常量函数。常量函数的意义在于,无法从调用函数的对象修改函数。建议在我们的程序中使用常量函数。
让我们看一个常量函数的例子。
示例
#include<iostream>
using namespace std;
class MyClass {
int value;
public:
MyClass(int val = 0) {
value = val;
}
int getVal() const {
//value = 10; [This line will generate compile time error as the function is constant]
return value;
}
};输出
The value is: 80
现在,我们将看到与常量函数相关的另一个重要内容。正如你从上面的例子中看到的,可以从任何类型的对象调用常量函数。但是,某些非常量函数无法从常量对象调用。
示例
#include<iostream>
using namespace std;
class MyClass {
int value;
public:
MyClass(int val = 0) {
value = val;
}
int getVal(){
return value;
}
};
main() {
const MyClass ob(80);
cout<< "The value is: " << ob.getVal();
}输出
[Error] passing 'const MyClass' as 'this' argument of 'int MyClass::getVal()' discards qualifiers [-fpermissive]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP