C++函数后加const的作用
先说结论:表示该函数不能修改所在类的成员变量。
比较常见的一个例子,平时使用Qt写界面时,QByteArray array;array.at(i)这种是不能被赋值的,因为at()的原型是char QBytearray::at(int i)const;
示例函数声明和定义
函数声明:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
int i_testValue;
mutable int mi_testValue;
public:
void setValue(int i_value)const; //
void setValue(int i_value);
int getValue();
};
#endif // MAINWINDOW_H
函数定义:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),i_testValue(0),mi_testValue(0)
{
}
MainWindow::~MainWindow()
{
}
void MainWindow::setValue(int i_value) const
{
Q_UNUSED(i_value);//消除未使用变量的编译警告
mi_testValue = 123;//mutable修饰的可以修改值
//i_testValue = 123;//不能对i_testValue赋值
}
void MainWindow::setValue(int i_value)
{
i_value = i_value;//消除未使用变量的编译警告
i_value = 123;
}
int MainWindow::getValue()
{
return i_testValue;
}
如上所示的函数声明和定义,
在定义中对普通private成员变量i_testValue赋值时,编译报错:
error: cannot assign to non-static data member within const member function 'setValue'
但是对mutable
修饰的变量,可以随意赋值。
解释原因:
在C++中,对象成员函数的调用存在this指针的隐式传递,
例如上图中类对象的函数调用:
MainWindow win;
win.setValue(123);
该函数的调用相当于:
win.setValue(MainWindow *const this,123);
赋值时,相当于:
this->i_testValue = 123;
在整个过程中this指向当前对象,存储当前对象的地址。
函数参数后加上的const,修饰 this指向的对象内容,相当于 :const MainWindow *const this, 代表 *this 是只读的,故而改变成员变量值时编译器会报错。
- Tips:Qt中对于定义却没使用的变量,会报警告。可以使用Q_UNUSED(**);来消除警告,也可以 i_value = i_value;这样消除警告。
原创内容,禁止转载
王雄 第一次更新于2021.03.04