c++ const笔记

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
#include <array>
#include <algorithm>

using namespace std;
using namespace cv;


/**
 * 1. const修饰常量:
 *      在C++中,const 常用于修饰常量,告诉编译器某值保持不变。
 *      需要注意的是,常量在定义之后就不能修改,因此定义时必须初始化。
 * 2. const修饰函数参数
 *      对于函数的入参,不管是什么数据类型,也不管是指针传递,还是引用传递,
 *      只要加了 const 修饰,就可以防止函数内意外修改该参数,起到保护作用。
 *
 * 3. const修饰返回值: 用 const 修饰返回的指针或引用,保护指针或引用的内容不被修改。
 *
 *      比如:
 *          int& GetAge()
 *          const int& GetAgeConst()
 *      两者的区别在于:前者返回的是一个左值,其引用的内容可以被修改;后者返回的是一个右值,其引用的内容不可被修改。
 *
 * 4. const修饰函数体
 *
 * @return
 */

// 1. const修饰常量:
const int HELLO = 4;

class classA {
    
    
public:
    string uname;
};

class classB {
    
    
public:
    string uname;
};

// 2. const修饰函数参数
void function(int *output, const classA &a, const classB *b) {
    
    
    // a.uname = "abc"; 报错
    // b->uname = "abc";报错
}

class Student {
    
    
public:
    int &getAge() {
    
    
        return m_age;
    }

    const int &getAgeConst() {
    
    
        return m_age;
    }

    void showAge() {
    
    
        cout << "Age: " << m_age << endl;
    }

    /**
     * const 修饰函数体时,放到函数体的行尾处,表明在该函数体内,
     * 不能修改对象的数据成员,且不能调用非 const 成员函数。
     * @param age
     */
    void setAgeConst(int age) const {
    
    
        // 在const修饰的成员函数里面不能为非静态的数据成员赋值
        // m_age = age; // cannot assign to non-static data member within const member function 'setAgeConst'
        // 不能调用非 const 成员函数
        // showAge这个成员方法参数this是'const Student'类型,但是showAge没有标识为const
        // showAge(); // 'this' argument to member function 'showAge' has type 'const Student', but function is not marked const
    }

private:
    int m_age = 0;
};


int main() {
    
    
    Student stu;
    stu.showAge();

    stu.getAge() = 5; // 会修改成员变量的值
    stu.showAge();

    // 不能为返回值赋值,因为getAgeConst函数返回一个const
    // stu.getAgeConst() = 8; // Cannot assign to return value because function 'getAgeConst' returns a const value
    stu.showAge();

    stu.setAgeConst(3);

    return 0;
}





猜你喜欢

转载自blog.csdn.net/guo20082200/article/details/132055721