C++. Error while passing pointer by reference.
Andrew Haley
aph@redhat.com
Fri Dec 5 10:10:00 GMT 2008
Kirill Berezin wrote:
> Hie.
>
> I crossed the very curious sample of code the gcc failed to compile.
> Here is the example:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> class test {
> public:
> int func(int*& a1){
> a2 = a1;
> return 0;
> }
> void print(){ printf("0x%X \n", a2);};
> private:
> int* a2;
> };
>
> int main(){
> int* a;
> int c;
> test b;
> //
> b.func(&c);
> b.print();
> return 0;
> }
> ц⌠++ prints the following error
>
> test05.cc: In function 'int main()':
> test05.cc:27: error: no matching function for call to 'test::func(int*)'
> test05.cc:12: note: candidates are: int test::func(int*&)
>
> I think that it is reasonable not to compile, because, for example, it
> would not possible to guess a correct function to overload. But The C++
> standard, at first glance, does not prohibit such a coding style.
Doesn't it?
&c yeilds an rvalue of type int*, and you're trying to pass it
as an lvalue to a function. I presume you're not actually
trying to use an rvalue reference here.
Fix it this way:
int func(int *const & a1){
a2 = a1;
return 0;
}
Andrew.
More information about the Gcc-help
mailing list