简体   繁体   English

C ++函数和指针

[英]C++ functions and pointers

I have an assignment to write a small program that includes using pointers and functions to find square root. 我分配了一个小程序,其中包括使用指针和函数查找平方根。 I'm getting an error that says "none of the 3 overloads could convert all the argument types" thanks for the help in advance 我收到一条错误消息:“ 3个重载中的任何一个都不能转换所有参数类型”,感谢您的提前帮助

here is the code i have so far. 这是我到目前为止的代码。 I know it's a mess, I hope you guys can help. 我知道那是一团糟,希望你们能提供帮助。

void SqrRt(unsigned long int *, unsigned long int *);

int main() {

    unsigned long int number, root;

    cout << "Type in any number greater than 0 to find it's square root: ";
    cin >> number;

    SqrRt(&number, &root);

    return 0;
}

void SqrRt(unsigned long int *num, unsigned long int *rt){

    if (num >= 0)
        rt = sqrt(num);
    else
        cout << "Invalid input! Number should be greater than 0!";
    }

sqrt can handle only numbers, not pointers to them , so everything you'll have to do is to dereference a pointer you're passing to sqrt . sqrt只能处理数字, 不能处理指向它们的指针 ,因此您要做的就是取消引用传递给sqrt的指针。

What's more, sqrt returns a number as well, so you should also dereference the pointer you're assigning to. 而且, sqrt返回一个数字,因此您还应该取消引用要分配给它的指针。

You need to rewrite rt = sqrt(num) to *rt = sqrt(*num) . 您需要将rt = sqrt(num)重写为*rt = sqrt(*num) The problem with your code is that you are not referring to the underlying object ie, the object the pointer points to. 代码的问题是您没有引用基础对象,即指针指向的对象。 I would suggest you to, if possible to use references as it is much easier to work with as compared to pointers. 我建议您尽可能使用引用,因为与指针相比,使用它要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM