📜  C++可变关键字

📅  最后修改于: 2021-05-26 02:55:02             🧑  作者: Mango

C++中的可变存储类说明符(或C++中使用可变关键字)
auto,register,static和extern是C中的存储类说明符。typedef也被视为C中的存储类说明符。C++也支持所有这些存储类说明符。除了此C++外,还添加了一个重要的存储类说明符,其名称是可变的。

有什么需要可变的?
有时,即使您不希望该函数更新类/结构的其他成员,也需要通过const函数来修改类/结构的一个或多个数据成员。使用mutable关键字可以轻松地执行此任务。考虑使用可变的示例。假设您去酒店,并命令服务员带些菜。下订单后,您突然决定更改食物的顺序。假设酒店提供了一种设施,可以更改订购的食物,并在发出第一个命令后的10分钟内再次接受新食物的订购。 10分钟后,订单将无法取消,旧订单也将无法替换为新订单。有关详细信息,请参见以下代码。

C++
#include 
#include 
using namespace std;
 
// Customer Class
class Customer {
    
    // class Variables
    string name;
    mutable string placedorder;
    int tableno;
    mutable int bill;
 
    // member methods
public:
   
    
    // constructor
    Customer(string s, string m, int a, int p)
    {
        name= s;
        placedorder=m;
        tableno = a;
        bill = p;
    }
     
    // to change the place holder
    void changePlacedOrder(string p) const
    {
        placedorder=p;
    }
   
    // change the bill
    void changeBill(int s) const { bill = s; }
   
    // to display
    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;
    }
};
 
// Driver code
int main()
{
    const Customer c1("Pravasi Meet", "Ice Cream", 3, 100);
    c1.display();
    c1.changePlacedOrder("GulabJammuns");
    c1.changeBill(150);
    c1.display();
    return 0;
}


CPP
// PROGRAM 1
#include 
using std::cout;
 
class Test {
public:
  int x;
  mutable int y;
  Test() { x = 4; y = 10; }
};
int main()
{
    const Test t1;
    t1.y = 20;
    cout << t1.y;
    return 0;
}


CPP
// PROGRAM 2
#include 
using std::cout;
 
class Test {
public:
  int x;
  mutable int y;
  Test() { x = 4; y = 10; }
};
int main()
{
    const Test t1;
    t1.x = 8;
    cout << t1.x;
    return 0;
}


输出
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

仔细观察上面程序的输出。从const函数更改了placeorderbill数据成员的值,因为它们被声明为可变的。

关键字mutable主要用于允许修改const对象的特定数据成员。当我们将函数声明为const时,传递给函数的this指针将变为const。将可变添加到变量允许const指针更改成员。
如果大多数成员应保持不变,但少数成员需要更新,则可变变量特别有用。即使声明为可变的数据成员是声明为const的对象的一部分,也可以对其进行修改。您不能将可变说明符与声明为static或const或reference的名称一起使用。
作为练习,请预测以下两个程序的输出。

CPP

// PROGRAM 1
#include 
using std::cout;
 
class Test {
public:
  int x;
  mutable int y;
  Test() { x = 4; y = 10; }
};
int main()
{
    const Test t1;
    t1.y = 20;
    cout << t1.y;
    return 0;
}

CPP

// PROGRAM 2
#include 
using std::cout;
 
class Test {
public:
  int x;
  mutable int y;
  Test() { x = 4; y = 10; }
};
int main()
{
    const Test t1;
    t1.x = 8;
    cout << t1.x;
    return 0;
}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”