zoukankan      html  css  js  c++  java
  • const 成员函数

    我们知道,在成员函数中,如果没有修改成员变量,应该给成员函数加上 const 修饰符,例如

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Foo
     6 {
     7 public:
     8     Foo(int x) : _x(x) {}
     9     int getX() const { return _x; }
    10 private:
    11     int _x;
    12 };
    13 
    14 int main()
    15 {
    16     Foo f(1);
    17     cout << f.getX() << endl;
    18     return 0;
    19 }

    如果不加 const 修饰符,当使用 const 对象调用成员函数时,编译报错:

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Foo
     6 {
     7 public:
     8     Foo(int x) : _x(x) {}
     9     int getX() { return _x; }
    10 private:
    11     int _x;
    12 };
    13 
    14 int main()
    15 {
    16     const Foo f(1);
    17     cout << f.getX() << endl;
    18     return 0;
    19 }
    jingyg@jingyg:~/share/mytest/cpp_test$ g++ -std=c++11 test.cpp 
    test.cpp: In function ?.nt main()?.
    test.cpp:17:17: error: passing ?.onst Foo?.as ?.his?.argument of ?.nt Foo::getX()?.discards qualifiers [-fpermissive]

    由测试可知:

      const 对象 非 const 对象
    const 成员函数 成功 成功
    非 const 成员函数 失败 成功

    const 对象有一个隐藏含义:保证成员变量不变。

    const 变量还可以作为函数签名的一部分:

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Foo
     6 {
     7 public:
     8     Foo(int x) : _x(x) {}
     9     int getX() const { cout << "with const" << endl; return _x; }
    10     int& getX() { cout << "without const" << endl; return _x; }
    11 private:
    12     int _x;
    13 };
    14 
    15 int main()
    16 {
    17     const Foo f(1);
    18     cout << f.getX() << endl;
    19 
    20     Foo f1(3);
    21     int& x = f1.getX();
    22     x = 2;
    23     cout << f1.getX() << endl;
    24     return 0;
    25 }
    jingyg@jingyg:~/share/mytest/cpp_test$ g++ -std=c++11 test.cpp 
    jingyg@jingyg:~/share/mytest/cpp_test$ ./a.out 
    with const
    1
    without const
    without const
    2

    可以看到 const 对象调用 const 成员函数,非 const 对象调用非 const 成员函数

  • 相关阅读:
    input只允许输入正整数
    CSS如何作小于1PX的边
    时间戳的处理
    图片转base64上传,视频同理。
    APIcloud微信支付和支付宝支付(方案2,主要在后台进行)
    H5滑条(input type=range)
    checkbox/radio 样式修改
    APIcloud制作APP 微信支付与支付宝支付
    JS获取鼠标左(右)滑事件
    DOM(Document object madle) 文档对象模型: 元素节点 文本节点 属性节点
  • 原文地址:https://www.cnblogs.com/jingyg/p/6971590.html
Copyright © 2011-2022 走看看