c ++重载具有不同参数的3个函数(int,* int,& int)

c++ overload 3 function with different parameters(int,*int,&int)

所以我有这个作业要做 "Using functions overloading define 3 functions with the same name but with different prams type (int, int*, int&) that will return the square root of the value." 好吧,我做到了,但我不知道它给我这个错误:"ambiguous call to overloaded function"。我尝试修复它但没有成功...... 这是我的代码,它非常简单:

#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <iostream>
using namespace std;

double rad(int);
double rad(int*);
double rad(int&);

int main(){
int a,*pt=&a;
cin>>a;
cout<<"Radical din "<<a<<" este "<<rad(a)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(pt)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(&a)<<endl;
return 0;
}

double rad(int x){
    return  (sqrt(x));
}
double rad(int *x){
    return  (sqrt(*x));
}
double rad(int &x){
    return  (sqrt(x));
}
int test_val = 5;    

// accept rvalue reference
double rad(int &&x) {
    return  (sqrt(x));
}
rad(5);

// accept pointer
double rad(int *x) {
    return  (sqrt(*x));
}
rad(&test_val);

// accept lvalue reference
double rad(int &x) {
    return  (sqrt(x));
}
rad(test_val);

鉴于这些声明:

double rad(int);   // (1)
double rad(int*);  // (2)
double rad(int&);  // (3)

处理 (2) 很容易。我们要么有指针,要么没有,不可能混淆。那么问题是,发生了什么:

int a;
rad(a);

嗯,这里 (1)(3) 都有效。实际上,在确定最佳可行候选人的规则中,两者之间没有任何偏好!这是一个 不明确的 调用,因此它总是无法编译。


请注意, 可以显式调用 (1) - 只需传入无法引用的 int

rad(4); // calls (1), since neither (2) nor (3) are possible

另请注意,即使使用像 a 这样的命名变量,也可以调用 (1)(3),但我们不能依赖重载解析来做到这一点。我们必须明确地告诉编译器我们想要哪个函数。为此,我们必须输入名称:

int a;
static_cast<double(*)(int)>(rad)(a);  // calls (1) explicitly
static_cast<double(*)(int&)>(rad)(a); // calls (3) explicitly

其他答案的前奏: 致电

rad(int)

rad(int& x)

看起来一样 - rad(a)。 行

rad(&a);

调用 rad(int*);

在第三种情况下,您应该使用右值引用 ('int&&') 而不是左值引用 ('int&'),以免混淆编译器。像这样:

#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <iostream>
using namespace std; 

double rad(int);
double rad(int*);
double rad(int&&);

int main(){
int a,*pt=&a;
cin>>a;
cout<<"Radical din "<<a<<" este "<<rad(a)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(pt)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(&a)<<endl;
return 0;
}

double rad(int x){
    return  (sqrt(x));
}
double rad(int *x){
    return  (sqrt(*x));
}
double rad(int &&x){
    return  (sqrt(x));
}