C++ 函数重载C++;指针

C++ 函数重载C++;指针,c++,overloading,C++,Overloading,我理解,如果参数数量不同,或者参数类型不同,重载函数是合法的 为什么只有返回类型的差异是不合法的 此外,超载是否合法: int hello(int x); int hello(int &z); 也 考虑一下编译器是如何计算出您想要调用的函数的。在第一个例子中,如果我写 int z = 5; int y = hello (z); 编译器将如何确定要调用哪个函数?但在第二个例子中 int z = 5; int y = hi (z); int u = hi (&z); 很清楚

我理解,如果参数数量不同,或者参数类型不同,重载函数是合法的

为什么只有返回类型的差异是不合法的

此外,超载是否合法:

int hello(int x);
int hello(int &z);


考虑一下编译器是如何计算出您想要调用的函数的。在第一个例子中,如果我写

int z = 5; 
int y = hello (z);
编译器将如何确定要调用哪个函数?但在第二个例子中

int z = 5; 
int y = hi (z);
int u = hi (&z);

很清楚要调用哪个函数。您不能仅在返回类型上重载,因为编译器需要参数来选择要调用的函数

由于
int
int&
int*
都是不同的类型,因此对它们进行重载是合法的

您还可以重载
const
,这在设计具有真正const正确性的类时非常有用

int hello(int);
int hello(int) const;

您不能重载返回类型,因为编译器不知道在完全通用的情况下使用哪个函数,特别是如果函数返回类型被调用方丢弃。

编译器无法仅通过返回值确定您要调用哪个函数。由于不需要捕获返回值,您可以编写:

hello( 1 ); // return int
hello( 2 ); // return float
从所能看到的情况来看,它们完全是相同的呼唤

是的,这是合法的,因为第一个hi采用引用,第二个hi采用内存地址。你可以这样称呼它:

hi( myNumber );
hi( &myNumber );

非常清晰。

对我来说很好,这不是同一种类型;例如,int x是整数,但int*z是整数的非指针。

编译器很难根据返回类型选择重载。在许多情况下,编译器没有显式语句来推断程序员指定的返回类型。即使这是可能的,程序员也会感到困惑

<强>假设

float func() {...};
int func() {...};

int x = func(); // OK, compiler may choose `int` version!
但是……怎么样

cout << func() + func();
cout允许在返回类型上重载实际上没有技术问题。在许多情况下,编译器知道函数调用所在的表达式需要什么类型,因此知道调用哪个函数。但也存在一些问题,例如,如果不使用返回值,则会产生歧义

至于函数,所有这些都是有效的重载。在
hello
的情况下,您可能会有一些歧义,这取决于您如何调用它,例如,如果您使用变量调用它,那么编译器实际上无法判断您想要哪个版本的
hello

您不能重载:

int hello(int x)   // 1
{
   return x;
}

int hello(int& x)  // 2
{
   return x;
}

int hello(int const& x) // 3
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Can't disambiguate between 1 and 2
   hello(10);   // Can't disambiguate between 1 and 3
}
int hello(int& x)  // 4
{
   return x;
}

int hello(int const& x) // 5
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Picks 4
   hello(10);   // Picks 5
}
但是,您可以过载:

int hello(int x)   // 1
{
   return x;
}

int hello(int& x)  // 2
{
   return x;
}

int hello(int const& x) // 3
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Can't disambiguate between 1 and 2
   hello(10);   // Can't disambiguate between 1 and 3
}
int hello(int& x)  // 4
{
   return x;
}

int hello(int const& x) // 5
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Picks 4
   hello(10);   // Picks 5
}

我认为你的主句有误导性。您可以重载这些,但在某些情况下,您将遇到不明确的解析错误。