2014-11-01 69 views
-1
#include <iostream> 

using namespace std; 

void reference(int &ref){ 
    cout << ref << endl; 
} 

void pointer(int *ref){ 
    cout << *ref << endl; 
} 

int main(){ 
    int *i = new int[1]; 
    *i = 10; 
    reference(*i); // fine 
    reference(i); // why not compiling!!! why not referencing to my pointer?? 
    pointer(i);  // fine 
} 

我想引用一个指针,因为我可以看到我被允许引用值而不是指针,为什么?为什么我们不能引用指针,而是值

+0

那么你可以:void指针(int *&ref){'。这是有点不清楚你实际上要求什么。 – 2014-11-01 08:15:44

+1

它不会崩溃,这是一个编译错误。 – 2014-11-01 08:20:06

+0

但为什么反对,似乎有效的问题? – 2014-11-01 08:45:30

回答

1

int*类型的对象不能被自动转换为int&的签名。

我认为你正在寻找的东西,如:

void reference(int& ref){ 
    cout << ref << endl; 
} 

void reference(int*& ref){ 
    cout << *ref << endl; 
} 

然后,您可以同时使用:

int main(){ 
    int *i = new int[1]; 
    *i = 10; 
    reference(*i); 
    reference(i); 
    return 0; 
} 
+0

然后,第一个引用调用将不起作用! – 2014-11-01 08:28:20

+0

你需要两种情况。 – 2014-11-01 08:29:24

+0

...并从主板返回一个值 – 2014-11-01 08:31:29

1

此行

reference(i); 

正试图用int *传递 - 不是一个``int`变量。因此不会编译。

参见功能

1

首先“崩溃”的是,你只能通过让后用一个名词编译器...

void reference(int &ref) 

这个函数在传递指针时引用整数作为它的参数整数通过

reference(i) 

你的函数的签名更改为类似: -

void reference(int* &ref) 

该呼叫工作。或更改呼叫类似于: -

int i; 
reference(i); 

为此功能工作。

+0

是的,我的意思是只有..什么函数参数类型,我应该用来获取指针int参考,谢谢 – 2014-11-01 08:28:21

相关问题