简体   繁体   English

C ++从int *到int的无效转换

[英]c++ invalid conversion from int* to int

I have the following C++ code: 我有以下C ++代码:

#include <iostream>

using namespace std;
template<class T>
T f(T x, T y)
{
    return x+y;
}
int f(int x, int y)
{
    return x-y;
}
int main()
{
    int *a=new int(3), b(23);
    cout<<f(a,b);
    return 0;
}

I get these errors: invalid conversion from 'int*' to 'int' 我收到这些错误:从“ int *”到“ int”的无效转换
initializing argument 1 of 'int f(int, int)' . 初始化'int f(int,int)'的参数1。 What does it mean ? 这是什么意思 ?

Thanks 谢谢

You need to dereference a in your call to f . 您需要在调用f取消引用a This is because a is a pointer to an int , while b is a bare int . 这是因为a是一个指向 int指针 ,而b是一个裸int Dereferencing a pointer to an int returns an int . 取消引用指向int的指针将返回一个int This results in the function f being called with two ints. 这导致函数f被两个整数调用。

cout<<f(*a,b);

Please tell us what exectly you want to achieve ?? 请告诉我们您想实现什么目标?

You need to use * operator to get value from 'a' pointer. 您需要使用*运算符从'a'指针获取值。

f(*a,b) //this invocation should work.

regardless of the fact that this code compiles without errors, it is ugly 不管该代码编译没有错误,它都是丑陋的

int f(int x, int y)
{
    return x-y;
}

In your above function, first parameter expects an integer argument, and not an address pointing to an integer value. 在上述函数中,第一个参数需要一个整数参数,而不是指向整数值的地址。 So what you need to make sure is that the data types of your FUNCTION PARAMETERS must match the data types of your FUNCTION ARGUMENTS. 因此,您需要确保功能参数的数据类型必须与功能参数的数据类型匹配。 Otherwise, such compilation errors will always pop up at compilation time. 否则,此类编译错误将始终在编译时弹出。

So in your case, there are following solutions to this problem: 因此,根据您的情况,有以下解决方案:

  1. change your function parameter int x to int* x Or 将函数参数int x更改为int * x或
  2. change your f(a,b) to f(*a,b) so that value of a is sent not address Or 将您的f(a,b)更改为f(* a,b),以便发送a的值而不是地址Or
  3. declare a as a simple integer like you did for b. 像对待b一样将a声明为简单整数。 Then while calling f function, send address of variable a. 然后在调用f函数时,发送变量a的地址。 Make sure for this option, function parameter int x should be changed to int* x 确保使用此选项,将函数参数int x更改为int * x

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

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