這個其實就是常函式,常函式內不可以修改成員屬性,但是在成員屬性后加mutable后依然可以在常函式中修改,
例如:下面的代碼是正確的,
// An highlighted block
class Person {
public:
void showPerson() const {
this->m_A = 100;
}
mutable int m_A;
};
但是,如果去掉mutable,結果就是錯誤的,會報錯,
提到常函式,不得不提到常物件,宣告物件前加const稱該物件為常對像,常對像只能呼叫常函式,例如:
在下面的函式中test 函式中就不會報錯,而在主函式中就會報錯,顯示(錯誤(活動) E1086 物件含有與成員 函式 “Person::fun” 不兼容的型別限定符),即:常對像只能呼叫常函式,showPerson為常函式,fun為普通函式,
// An highlighted block
#include<iostream>
using namespace std;
class Person {
public:
void showPerson() const {
this->m_A = 100;
}
void fun() {
}
mutable int m_A;
};
void test() {
const Person p;
p.m_A = 100;
p.showPerson();
}
int main() {
const Person p;
p.fun();
}
大家的贊是對我最大的支持,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/256709.html
標籤:其他
上一篇:天高任鳥飛,海闊憑魚躍
