3

Anything wrong with my code below? I got the compile error!

typedef unsigned char BYTE;

void foo(char* & p)
{
 return;
}

int main()
{
  BYTE * buffer;
  // error C2664: 'foo' : cannot convert parameter 1 from 'char *' to 'char *&'
  foo ((char*)buffer);

  return 0;
}

Thanks in advance, George

4

7 回答 7

14

When you cast the BYTE* to char* a unnamed temporary entity is created with the type char*. The function you call takes a reference to a char* but you can't take a reference to such a temporary entity because it is not a real variable.

于 2009-02-15T18:36:49.523 回答
7

You can perform a reinterpret_cast<char*&> instead of a static cast

foo (reinterpret_cast<char*&>(buffer));

Or, you can make the argument a const reference:

void foo(char* const & p)
{
    return;
}
于 2009-02-15T18:56:30.677 回答
4

The parameter of foo is a reference-to-a-pointer. buffer is a BYTE pointer. Reference require an exact match, assignment-compatible won't do.

Two solutions:

1) you probably don't need the '&' in front of p. Loose it and the code will compile.

2) Use a correctly typed variable so the reference will work:

 BYTE * buffer;
 char * b = (char *) buffer;
 foo (b);
 buffer = (BYTE*) b;  // because foo may change b
于 2009-02-15T18:39:25.587 回答
2

指针是一个“buffer左值”,但是当对它应用强制转换操作时,表达式:

(char*) buffer

是一个“右值”(实际上是一个“可修改的右值”——但我认为这只在即将到来的 C++0x 中很重要)。非常量引用不能绑定到右值。

但是,const引用可以绑定到右值。因此,对您的程序的以下修改将编译:

void foo(char* const& p)  // added 'const'

Stephan T. Lavavej 最近发布了一篇博客文章,其中包含有关左值、右值和引用的大量信息:

这篇文章实际上是关于 C++0x 中的新“右值引用”,但它很好地解释了左值和右值是什么,以及它们如何能够和不能与 C++98 中的引用一起使用。这是一个很长的阅读,但非常值得。

于 2009-02-15T20:06:23.597 回答
1

You are trying to pass a variable reference, but there is no such variable of type char* you could refer to.

It should work this way if I remember correctly:

BYTE * buffer;
char* ptr = (char*)buffer;
foo(ptr); // now you have a matching variable to refer to. 

Maybe it would be easier to just pass a value instead of a reference.

于 2009-02-15T18:38:11.923 回答
1

Firstly, when you say

(char)buffer

You are lying to the compiler - buffer is pointer, not a char.

Secondly, even if the cast worked, it would produce a temporary, which cannot be bound to a non-const reference.

So, yes, there are at least two things wrong with your code.

于 2009-02-15T18:38:25.230 回答
1

Write it like this:

int main() { 
  BYTE * buffer; 
  char* pbuf = (char*)buffer;
  foo(pbuf);
}
于 2009-02-15T18:39:18.440 回答