我有代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
void func(const int& a)
{
std::cout << "func(const)" << std::endl;
}
void func(volatile int& a)
{
std::cout << "func(volatile)" << std::endl;
}
void func(const volatile int& a)
{
std::cout << "func(const volatile)" << std::endl;
}
int main()
{
const int a = 0;
const volatile int b = 0;
volatile int c = 0;
func(a);
func(b);
func(c);
system("pause");
return 0;
}
上面的代码显示了基于参数是否为 const/volatile 的重载。但是,如果我将参数从 更改int&
为int
,则代码将不再编译,并且我无法根据 const/volatile 参数类型重载。我不明白为什么如果 int 通过引用传递,我们可以基于 const 和 volatile 重载,但如果它通过值传递则不行?
编辑我应该强调我理解引用的作用-我不明白为什么允许引用别名在 const 上重载但普通的 int 不允许。