zoukankan      html  css  js  c++  java
  • const的重载

    class A
    {
    private:
    	int a;
    public:
    	A(int x) :a(x){}//构造函数并不能重载
    	void display(){ cout << "non-const" << endl; }
    	void display()const{ cout << "const" << endl; }
    	void show(int x){ cout << "non-const " << x << endl; }
    	void show(const int x){ cout << "const " << x << endl; }//这是错误的重载,甚至不能通过编译器
    };
    
    void f(const int a)//并不能进行这样的重载,甚至不能通过编译器
    {
    	cout << "const" << endl;
    }
    
    void f(int a)
    {
    	cout << "const" << endl;
    }
    
    int main()
    {
    	int a1 = 1;//当作变量用
    	const int a2 = 2;//当作常数用
    	A a(2);//对象a
    	const A c(3);//常对象c
    	a.display();//用non-const
    	c.display();//用const
    	a.show(a1);//
    	a.show(a2);//
    	
    }
    

      补充回一句容易混淆的话:

    普通对象可以使用常函数

    当有const重载的情况下,优先使用普通函数版本

    常数对象只能使用常函数

  • 相关阅读:
    希尔排序
    折半插入排序
    自学git心得-2
    读书笔记-1 《人月神话》
    USTCCourseCommunity 项目介绍
    自学git心得-1
    HDU 2006 求奇数的乘积
    HDU 2007 平方和与立方和
    HDU 2005 第几天?
    HDU 2004 成绩转换
  • 原文地址:https://www.cnblogs.com/vhyc/p/5587831.html
Copyright © 2011-2022 走看看