C++ const常量对象、常量成员函数和常引用

01 常量对象

若是不但愿某个对象的值被改变,则定义该对象的时候能够在前面加const关键字函数

class CTest
{
public:
    void SetValue() {}
private:
    int m_value;
};

const CTest obj; // 常量对象

02 常量成员函数

在类的成员函数后面能够加const关键字,则该成员函数成为常量成员函数。指针

  • 在常量成员函数中不能修改为员变量的值(静态成员变量除外);
  • 也不能调用同类的 非 常量成员函数(静态成员函数除外)
class Sample
{
public:
    void GetValue() const {} // 常量成员函数
    void func(){}
    int m_value;
};

void Sample::GetValue() const // 常量成员函数
{
    value = 0; // 出错
    func();    // 出错
}

int main()
{
    const Sample obj;
    obj.value = 100; // 出错,常量对象不能够被修改
    obj.func(); // 出错,常量对象上面不能执行 非 常量成员函数
    obj.GetValue // OK,常量对象上能够执行常量成员函数
    
    return 0;
}

03 常量成员函数的重载

两个成员函数,名字和参数表都同样,可是一个是const,一个不是,那么是算是重载。code

class Sample
{
public:
    Sample() { m_value = 1; }
    int GetValue() const { return m_value; } // 常量成员函数
    int GetValue() { return 2*m_value; } // 普通成员函数
    int m_value;
};

int main()
{
    const Sample obj1;
    std::cout << "常量成员函数 " << obj1.GetValue() << std::endl;
    
    Sample obj2;
    std::cout << "普通成员函数 " << obj2.GetValue() << std::endl;
}

执行结果:对象

常量成员函数 1
普通成员函数 2

04 常引用

引用前面能够加const关键字,成为常引用。不能经过常引用,修改其引用的变量的。class

const int & r = n;
r = 5; // error
n = 4; // ok!

对象做为函数的参数时,生产该对象参数是须要调用复制构造函数的,这样效率就比较低。用指针做为参数,代码又很差看,如何解决呢?效率

能够用对象的引用做为参数,防止引起复制构造函数,如:变量

class Sample
{
    ...  
};

void Func(Sample & o) // 对象的引用做为参数
{
    ...
}

可是有个问题,对象引用做为函数的参数有必定的风险性,若函数中不当心修改了形参0,则实参也会跟着变,这可能不是咱们想要的,如何避免呢?构造函数

能够用对象的常引用做为参数,如:引用

class Sample
{
    ...  
};

void Func(const Sample & o) // 对象的常引用做为参数
{
    ...
}

这样函数中就能确保不会出现无心中更改o值的语句了。error

相关文章
相关标签/搜索