zoukankan      html  css  js  c++  java
  • C++同时存在const与non-const函数的类调用

    当对象同时又const与non-const函数时,我们传进去的参数会调用什么?

    答:常量对象就调用const类型的函数,非常量对象两个都可以调用

    测试代码

    #include<iostream>
    #include<algorithm>
    #include<string>
    using namespace std;
    
    class A
    {
    
    private:
        std::string s;
    public:
        A()
        {
            s = "abcdefg";
        }
    
        /*
        同时存在const和non-const,调用时会调用哪个函数
        */
        void test(int a) const
        {
            a = 5;
            cout << "const" << endl;
        }
        void test(int a)
        {
            cout << "non const" << endl;
        }
        const char& operator[](int b)const
        {
            std::cout << "const" << endl;
            return s[b];
        }
        char& operator[](int b)
        {
            std::cout << "non-const" << std::endl;
            return s[b];
        }
    };
    
    
    /*
    测试cnonst与non-const
    */
    void testConst()
    {
        A a;
        int b = 2;
        const int c = 3;
        a.test(2);
        a.test(b);
        a.test(c);
        a[2];
        a[b];
        a[c];
        const A d;
        d.test(2);
        d.test(b);
        d.test(c);
        d[2];
        d[b];
        d[c];
    
    }
    
    int main()
    {
        testConst();
    }
  • 相关阅读:
    uva 10192 Vacation(最长公共子)
    SolrCloud应用简介
    2015第43周一solr相关概念
    2015第42周日
    2015第42周六Pgsql全文索引
    Java注解
    2015第42周四
    2015第42周三
    JS原型函数相关基础知识
    2015第42周一爬虫与反爬虫
  • 原文地址:https://www.cnblogs.com/pppyyyzzz/p/14339191.html
Copyright © 2011-2022 走看看