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重载的情况下,优先使用普通函数版本

    常数对象只能使用常函数

  • 相关阅读:
    C++ 虚成员函数和动态联编
    C++ 多态公有继承
    C++ 继承特性
    C++ 公有派生
    C++ 基类与派生类
    C++ 类继承
    C++ 伪私有方法
    C++ new失败
    mysql用户授权
    linux时间设置
  • 原文地址:https://www.cnblogs.com/vhyc/p/5587831.html
Copyright © 2011-2022 走看看