C++ 常量和volatile上的重载-为什么它通过引用工作?
我有密码:C++ 常量和volatile上的重载-为什么它通过引用工作?,c++,constants,overloading,volatile,C++,Constants,Overloading,Volatile,我有密码: #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)" << st
#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;
}
#包括“stdafx.h”
#包括
使用名称空间std;
无效函数(常量int&a)
{
std::cout问题是在重载解析中忽略了顶级常量和/或volatile
void foo(const int);
完全一样
void foo(int);
这是一条语言规则,因为参数是按值传递的。另一方面,引用const/volatile
或指向const/volatile
的指针具有不同的含义:不允许对它们引用或指向的对象调用非const/volatile方法因此,const
volatile
不是顶级
void foo(int& i); // can modify what i refers to, and this has effects outside of foo.
void foo(const int& i); // cannot modify what i refers to
上述两个声明具有非常不同的语义,因此该语言在重载解析方面使它们区别开来。也许从函数中退一步,看看用例本身是有用的
首先,我们将定义一个整数和一个常量整数,以便在示例中使用:
int anInt = 1;
const int aConstInt = 1;
接下来,我们来看看使用这些变量设置其他整数和常量整数的值时会发生什么:
int a = anInt; // This works, we can set an int's value
// using an int
int b = aConstInt; // This works, we can set an int's value
// using a const int
const int c = anInt; // This works, we can set a const int's value
// using an int
const int d = aConstInt; // This works, we can set a const int's value
// using a const int
如您所见,无法解决基于行为选择函数的哪个重载(int和const都可以接受常量int,同样,int和const都可以接受int)
接下来,我们将了解将第一组变量传递给引用时会发生什么:
int& a = anInt; // This works because we are using a
// non-constant reference to access a
// non-constant variable.
int& b = aConstInt; // This will NOT work because we are
// trying to access a constant
// variable through a non-constant
// reference (i.e. we could
// potentially change a constant
// variable through the non-const
// reference).
const int& c = anInt; // This works because we are using a
// constant reference (i.e. "I cannot
// try to change the referenced
// variable using this reference") to
// a non-constant variable.
const int& d = aConstInt; // This will work because we are trying
// to access a constant variable
// through a constant reference.
如您所见,在区分int引用和const int引用时,可以有一些有用的行为(即,当需要常量引用类型时,不允许创建非常量引用).你能详细说明int&和int之间的区别吗?我以为引用只是另一个变量的别名?所以int&和int没有区别?一个只是别名?@user997112当你使用引用时,不进行复制。当你使用纯传递值时,参数被复制。@user997112我试图详细说明。在reference中在这种情况下,语义是完全不同的。对于语言来说,有单独的重载是很有用的。没有重载会让人困惑。@H2CO3我知道这一点,但我只是问“为什么基于常量的引用重载可以?”。我不明白为什么引用/指针是特殊的?实际上我有点理解为什么指针是因为指针本身就是一种类型?@user997112是的,引用只是别名。但是,将别名带到现有的int
的函数与要求调用方创建int
和hand的副本的函数不同这与功能有关。