c ++: three

C ++: three

  For shared data protection, we can use constant, while using the data also prevents the data from being changed, you can effectively protect data.

Often the object

  Often the object must be to use the "const" keyword specifies the object name often objects when defining object. Often the value of the data members of the object can not be changed within a target period of survival.

  Data member often object to the variable and often must have an initial value, such as

Time const t1(12,34,36); //定义t1为常对象
//或者写为 const Time t1(12,34,36);
//两种写法都是正确的。

That is often the object must be initialized and can not be updated .

E.g:
1
2

Often a member function

  Similarly, using the keyword "const" modified function is often a member function.
Use as follows:

void print() const;//类型说明符  函数名  const;

Regular member functions can access the data members often object, but still often not allowed to modify the value of the object data members. const is part of the function type, should have the const keyword in function declaration and definition of functions, do not add const when calling.
E.g:

#include <iostream>
using namespace std;
class R
{
public:
    R(int r1, int r2) :r1(r1), r2(r2){}
    void print();
    void print() const;
private:
    int r1,r2;
};
 
void R::print() 
{
    cout << r1 << ";" << r2 << endl;
}
 void R::print() const
{
     cout << r1 << ";" << r2 << endl;
  }


int main()
{
    R a(5,4);
    a.print();
    const R b(20, 52);
    b.print();
    
    return 0;
}

输出结果为:
5;4
20;52

On the basis of experiments carried out for the value const b can not be modified, added to the change function in the original function, for changing r1, r2 values, the specific code is as follows:

#include <iostream>
using namespace std;

class R
{
public:
    R(int r1, int r2) :r1(r1), r2(r2){}
    void print();
    void print() const;
    void change();
private:
    int r1,r2;
};
 
void R::print() 
{
    cout << r1 << ";" << r2 << endl;
}
 void R::print() const
{
     cout << r1 << ";" << r2 << endl;
  }
 void R::change()
 {
     r1 = r1 + 1;
     r2 = r2 + 1;
     cout << r1 << ";"<<r2 << endl;
 }

int main()
{
    R a(5,4);
    a.print();
    const R b(20, 52);
    b.print();
    a.change();
    return 0;
}
运行结果为:
5;4
20;52
6;5

Change the value of a function proved the successful change, and the main function of a.change (); statement to b.change ();
time compiler error:
1

It is proved

Guess you like

Origin www.cnblogs.com/Drac/p/11610372.html