美文网首页
C++ mutable 用法

C++ mutable 用法

作者: 直木的散装笔记 | 来源:发表于2020-07-09 13:34 被阅读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/

相关文章

  • C++ mutable 用法

    为什么需要mutable? 有时,可能需要通过const函数去更新一个或多个类成员变量,但是不希望函数更新其他成员...

  • C++中const、volatile、mutable的用法

    参考博文:https://www.cnblogs.com/xkfz007/articles/2419540.html

  • C/C++关键字介绍

    一、 typedef typedef为C/C++的关键字,与auto、extern、mutable、static、...

  • C++ ofstream和ifstream详细用法

    C++ ofstream和ifstream详细用法

  • C++编程规范

    序 C++用法很多,包容性也比较强。一个C++的工程可能包含了各种各样没见过的用法。本篇内容主要是参照谷歌C++标...

  • 2019-06-10

    实现类 DeltaPackedLongValuesPackedInts.Mutable mutable = Pa...

  • Kotlin学习笔记——基础语法篇之控制语句

    if...else... 用法 Kotlin中if...else...基本用法与C/C++,java中相同 例子 ...

  • mutable

    1,理解 mutable字面意思是可变的,其实直接定义的local variable都是可变的,所以mutable...

  • C++ 基础

    RAII惯用法:C++资源管理的利器 一文说尽C++赋值运算符重载函数(operator=) C 和 C++ 区别...

  • c++ new用法

    本文关于c++的基础用法和高级用法 1.基础用法 new A()进行了如下操作:(1) 在堆上分配了存储空间(2)...

网友评论

      本文标题:C++ mutable 用法

      本文链接:https://www.haomeiwen.com/subject/ccvjcktx.html