zoukankan      html  css  js  c++  java
  • 当const放在function声明后

    #include <iostream>
    
    class MyClass
    {
    private:
        int counter;
    public:
        void Foo()
        { 
            std::cout << "Foo" << std::endl;    
        }
    
        void Foo() const
        {
            std::cout << "Foo const" << std::endl;
        }
    
    };
    
    int main()
    {
        MyClass cc;
        const MyClass& ccc = cc;
        cc.Foo();
        ccc.Foo();
    }
    

    输出结果

    Foo
    Foo const
    

    未使用const的方程,可以改变其实例成员,对使用了const的方程却不可。如果你使用以下方程,const方程中涉及实例比变量变更的语句不会被编译。

      void Foo()
        {
            counter++; //this works
            std::cout << "Foo" << std::endl;    
        }
    
        void Foo() const
        {
            counter++; //this will not compile
            std::cout << "Foo const" << std::endl;
        }
    

    若想在const方程中变更实例变量,可声明实例变量为mutable类型。

    #include <iostream>
    
    class MyClass
    {
    private:
        mutable int counter;
    public:
    
        MyClass() : counter(0) {}
    
        void Foo()
        {
            counter++;
            std::cout << "Foo" << std::endl;    
        }
    
        void Foo() const
        {
            counter++;
            std::cout << "Foo const" << std::endl;
        }
    
        int GetInvocations() const
        {
            return counter;
        }
    };
    
    int main(void)
    {
        MyClass cc;
        const MyClass& ccc = cc;
        cc.Foo();
        ccc.Foo();
        std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << endl;
    }
    

    输出结果

    Foo
    Foo const
    Foo has been invoked 2 times
    
  • 相关阅读:
    不忘初心,方得始终
    【读书笔记】Windows核心编程
    工作心得
    2015年随记
    微信开发的黑魔法
    [cssTopic]浏览器兼容性问题整理 css问题集 ie6常见问题【转】
    获取微信用户openid
    Spring Boot应用开发起步
    一种在Java中跨ClassLoader的方法调用的实现
    H5语义化标签
  • 原文地址:https://www.cnblogs.com/liez/p/11980599.html
Copyright © 2011-2022 走看看