Explicit and mutable are two key words in c++.
1. Explicit keyword
Constructor explicit iostream constructor explicit iostream constructor explicit iostream constructor explicit iostream constructor explicit iostream constructor explicit iostream
Explicit is used to prevent implicit conversions defined by constructors. Start with code like this: explicit
#include <iostream>
class Base
{
private:
int a;
public:
Base(intp_a){ a = p_a; } ~Base() {}void print(a)
{
std::cout << "a="<< a << std::endl; }};int main(a)
{
Base base = 5;
base.print(a); base =6;
base.print(a);return 0;
}
Copy the code
Class Base = explicit; class Base = explicit; class Base = explicit; class Base = explicit; For the member variable assignment, this also calculate, as when he is in the structure, but in the base = 6 this line of code, very wide of the mark, did not call any set function, just changed the value of private members, this is equivalent to, put the money inside your house, someone else can partition to modify the number of your money, think about it, You have $10,000 at home, and one finger turns into $100, isn’t that scary?
When the constructor is preceded by the explicit keyword, the code can no longer be written in this way.
// The constructor is preceded by explicit
explicit Base(int p_a){ a = p_a; }Copy the code
CPP :19:14: error: conversion from ‘int’ to non-scalar type ‘Base’ requested, which will prevent anyone from changing the amount of your money.
The compiler makes an implicit conversion at compile time, based on the current definition and constructor, before the keyword is declared. However, when the compiler finds explicit, it no longer makes an implicit conversion. In this case, the value types on both sides of the equal sign are obviously different, which will result in a compilation error.
Summary: Explicit is not allowed to make changes to the amount of money in my home through the wall, you have to be in the house to make the changes.
2. The mutable keyword
When a member function of a class is declared to be const, it is not possible to modify a class’s data members by using a mutable method, such as:
#include <iostream>
class demo
{
public:
int getCnt(a) const
{
m_nCount++;
return m_nCount;
}
private:
int m_nCount;
};
int main(a)
{
return 0;
}
Copy the code
Test. CPP :13: error: increment of data-member ‘demo::m_nCount’ in read-only structure
#include <iostream>
class demo
{
public:
int getCnt(a) const
{
m_nCount++;
return m_nCount;
}
private:
mutable int m_nCount;
};
int main(a)
{
return 0;
}
Copy the code
Add a mutable keyword in front of the int type, and the compilation passes.
Summary: Mutable allows you to place certain mutable objects in a fixed house.