C++ const修饰符

const修饰符可以修饰数据成员、成员函数和类对象。接下来分别进行解释:

1.修饰数据成员

修饰数据成员的时候,初始化只能在参数列表里,被const修饰的数据成员,不能被修改。如下代码所示:

class Const_test{
public:
    Const_test(int v):value(v){
        
    }
private:
    const int value;
};

2.修饰成员函数

const放置的位置: 函数声明之后,实现体之前。要求在声明和定义处都要有const修饰。const所修饰的成员函数能访问const和非const数据成员,但不能修改非const数据成员,只能访问const成员函数,不能访问非const成员函数。   

构成重载:const对象只能调用const成员函数。非const成员对象,优先调用非const成员函数,若无,则可调用const成员函数。

class Const_test{
public:
    Const_test(int v):value(v){

    }
    void display()const{
        age = 10;   //错误
        int temp = 10; //正确
        temp = age;
        print();//错误
    }
    void dispaly(){//重载

    }

    void print(){

    }

private:
    int age;
    const int value;
};
3.修饰类类对象

const修饰函数,是从函数层面,不修改数据。const修饰对象,是从对象的层面,不修改数据。只能调用const成员函数。



猜你喜欢

转载自blog.csdn.net/u011074149/article/details/80274726