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 成员函数

  • 相关阅读:
    监听器、过滤器
    最详细的Log4j使用教程
    Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules
    Unsupported major.minor version 52.0
    jdk安装
    数据库建表
    SpringMVC学习系列-后记 解决GET请求时中文乱码的问题
    面向对象中的常用魔术方法
    面向对象中的修饰关键词
    面向对象三大特性之二--【继承】
  • 原文地址:https://www.cnblogs.com/jingyg/p/6971590.html
Copyright © 2011-2022 走看看