C++ mutable 用法

2020-07-09  本文已影响0人  直木的散装笔记

为什么需要mutable?

有时,可能需要通过const函数去更新一个或多个类成员变量,但是不希望函数更新其他成员变量。使用mutable关键字可以轻松执行此任务。考虑使用可变的示例。假设您去酒店,并命令服务员带些菜。下订单后,您突然决定更改食物的顺序。假设酒店提供了一种设施,可以更改点餐的食物,并在发出第一个命令后的10分钟内再次接受新食物的命令。 10分钟后,订单将无法取消,旧订单也将无法替换为新订单。

#include <iostream> 
#include <string.h> 
using std::cout; 
using std::endl; 

class Customer 
{ 
    char name[25]; 
    mutable char placedorder[50]; 
    int tableno; 
    mutable int bill; 
public: 
    Customer(char* s, char* m, int a, int p) 
    { 
        strcpy(name, s); 
        strcpy(placedorder, m); 
        tableno = a; 
        bill = p; 
    } 
    void changePlacedOrder(char* p) const
    { 
        strcpy(placedorder, p); 
    } 
    void changeBill(int s) const
    { 
        bill = s; 
    } 
    void display() const
    { 
        cout << "Customer name is: " << name << endl; 
        cout << "Food ordered by customer is: " << placedorder << endl; 
        cout << "table no is: " << tableno << endl; 
        cout << "Total payable amount: " << bill << endl; 
    } 
}; 

int main() 
{ 
    const Customer c1("Pravasi Meet", "Ice Cream", 3, 100); 
    c1.display(); 
    c1.changePlacedOrder("GulabJammuns"); 
    c1.changeBill(150); 
    c1.display(); 
    return 0; 
}

Output:

Customer name is: Pravasi Meet
Food ordered by customer is: Ice Cream
table no is: 3
Total payable amount: 100
Customer name is: Pravasi Meet
Food ordered by customer is: GulabJammuns
table no is: 3
Total payable amount: 150 

参考资料:https://www.geeksforgeeks.org/c-mutable-keyword/

上一篇下一篇

猜你喜欢

热点阅读