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
    
  • 相关阅读:
    转载——rdis安装yum版本
    Lc28_strStr kmp字符串匹配
    关于 哈希的总结
    Lc344_反转字符串
    Lc383_赎金信
    Lc454_四数相加 II
    Lc1_俩数之和
    推荐4款个人珍藏的IDEA插件!帮你写出不那么差的代码
    ZUC-生成随机序列
    移位运算
  • 原文地址:https://www.cnblogs.com/liez/p/11980599.html
Copyright © 2011-2022 走看看