2015-10-16 105 views
-1

我有以下代码:无效的转换,从“诠释”到“诠释*” [-fpermissive]

#include <stdio.h> 
#include <stdlib.h> 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstdlib> 

#define initialSize 50 

//Public GCC compiler-friendly macros 

#define n argv[2] 

using namespace std; 

struct Point { 
    int x; 
    int y; 
    int z; 
}; 


int smallest(Point* p, int n); 

int size = 0, max_size = initialSize; 
int *A = new int[max_size]; 


int main(int argc, char* argv[]) { 
     int test; 
     Point* p = new Point(); 
     smallest(p, test); 

    return 0; 
} 

int smallest(Point *p, int n) { 
return 0; 
} 

从我的理解,这应该是有效的语法C++。不过,我得到以下编译错误:

test.cpp:32:20: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive] 
test.cpp:23:5: error: initializing argument 2 of ‘int smallest(Point*, int*)’ [-fpermissive] 

我使用命令:g++ -std=c++11 test.cpp

编辑:添加了完整的源代码,而不是片段。尝试在不同的环境,但遇到相同的编译错误。

+7

编译器认为'最小'采用'int *'作为其第二个参数,而不是'int'。最有可能的是,这里显示的代码实际上并不是实际编译的代码。你已经显示的代码[编译没有错误](http://rextester.com/OCA2667) –

+0

不希望使用指针。声明你的变量为'Point p;'。这是C++语言,而不是C#或Java - 每个变量都不需要“新”。另外,考虑通过引用传递'Point'。 –

+0

谢谢你的评论。 @IgorTandetnik为什么编译器认为第二个参数是int *指针,而不是int? – WCGPR0

回答

1

第一:

#define n argv[2] 

二:

int smallest(Point* p, int n); 

三:

int test; 

第四:

smallest(p, test); 

我不知道为什么你需要定义,但它肯定他会这样奇怪的行为。

2

您发布的代码正确编译。

尽量不要使用指针:

int smallest(const Point& p, int value) 
{ 
    return 0; 
} 

int main(void) 
{ 
    int test = 15; 
    Point p; 
    smallest(p, test); 
    return EXIT_SUCCESS; 
} 
+0

这是有效的。也许我没有正确使用指针?现在我想到了,我肯定应该使用引用。然而,出于好奇,我在代码中的语法错误在哪里? – WCGPR0