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

常数对象只能使用常函数

posted on 2016-06-15 16:01  Kooing  阅读(188)  评论(0编辑  收藏  举报

导航