美文网首页
常量(const)

常量(const)

作者: qyfl | 来源:发表于2017-12-15 22:35 被阅读0次

const

  • 形容参数

如果函数接受的参数在函数中不会被改变值,加上 const 。

void foo(const int a) {
    cout << a;
}
  • 形容函数

如果函数中的功能很简单,没有改变变量的值,加上 const 。

class A {
private:
    int a, b;

public:
    A(int x, int y) : a(x), b(y) { }
    int getA() const { return a; }
};

如果不加 const ,以下的调用会报错。

创建了一个不希望被改变的对象,调用函数时,因为设计者没有加 const ,所以调用不了。

const A tmp(1, 2);
cout << tmp.getA();     // error

相关文章

网友评论

      本文标题:常量(const)

      本文链接:https://www.haomeiwen.com/subject/qrdjwxtx.html